2012-10-10 90 views
0

這是我想要執行存儲過程:SQL Server 2008 R2的無效的對象名稱錯誤

Alter PROCEDURE pro_worst_supplier_test 
@datey nvarchar(4), @datem nvarchar(2) 
    AS 
    BEGIN 
-- SET NOCOUNT ON added to prevent extra result sets from 
-- interfering with SELECT statements. 
SET NOCOUNT ON; 
-- Insert statements for procedure here 

select y.CompanyName from (SELECT s.CompanyName,(select min(t.b) from (select (round(sum(OD.Quantity * (1-OD.Discount) * OD.UnitPrice),0)) as b from [Order Details] group by ProductID) t) as q 
FROM ((((Products p 
inner join [Order Details] OD on p.ProductID=OD.ProductID) 
inner join Categories c on p.CategoryID=c.CategoryID) 
inner join Suppliers s on p.SupplierID=s.SupplierID) 
inner join Orders o on o.OrderID=od.OrderID) 
where c.CategoryName='Produce' AND SUBSTRING(CONVERT(nvarchar(22), o.OrderDate, 111),1,4)[email protected] AND SUBSTRING(CONVERT(nvarchar(22),o.OrderDate, 111),6,2)[email protected] 
group by s.CompanyName) y 
where q=(select MIN(q)from y) 
END 
GO 

當我試圖通過

exec proc_worst_supplier_test '1998','04' 

我得到一個錯誤來執行它

無效的對象名稱'y'

回答

0

試試這個:

;WITH CTE as (
SELECT s.CompanyName,(select min(t.b) from (select (round(sum(OD.Quantity * (1-OD.Discount) * OD.UnitPrice),0)) as b from [Order Details] group by ProductID) t) as q 
FROM ((((Products p 
inner join [Order Details] OD on p.ProductID=OD.ProductID) 
inner join Categories c on p.CategoryID=c.CategoryID) 
inner join Suppliers s on p.SupplierID=s.SupplierID) 
inner join Orders o on o.OrderID=od.OrderID) 
where c.CategoryName='Produce' AND SUBSTRING(CONVERT(nvarchar(22), o.OrderDate, 111),1,4)[email protected] AND SUBSTRING(CONVERT(nvarchar(22),o.OrderDate, 111),6,2)[email protected] 
group by s.CompanyName 
) 

select CompanyName from CTE where q=(select MIN(q) from CTE) 
+0

非常感謝。我在谷歌搜索了什麼CTE,但我仍然無法弄清楚我原來的問題是什麼。 – Mo0

+0

在你原來的查詢中你引用了派生列。在同一個查詢中,你不能使用它們。 – AnandPhadke

相關問題