使用公用表表达式时列名无效

时间:2014-03-12 18:42:15

标签: sql-server tsql sql-server-2005 procedure

下面是使用公用表表达式的存储过程。但是我继续获取无效的列名称' SellPrice'。您能否告诉我哪里出错?

Create proc [dbo].[GetDetails]
@fromdate datetime,
@todate datetime
as
Begin
with cte as
(
   select
      b.ItemCode,
      b.Description,
      sum(c.Quantity) as Qty,
      sum(b.NetPrice) as NetPrice,
      sum(b.SellPrice) as SellPrice
   from Invoicedetails a inner
      join ItemDetails b
         on a.InvoiceID=b.InvoiceID
      inner join BatchDetails c
         on b.InvoiceID=c.InvoiceID and b.ItemID=c.ItemID
   where a.IsDeleted=0 and a.InvoiceDate between @fromdate and @todate
)
select
   cte.ItemCode,
   cte.Description,
   (NetPrice/Qty) as [AvgNetPrice],
   (SellPrice/Qty) as [AvgSellPrice], ((SellPrice/Qty)  -(NetPrice/Qty) ) as ProfitAmount
from cte
End

* * 有趣的是当我将此"(SellPrice / Qty)删除为[AvgSellPrice]"它运作良好。但当我将(SellPrice / Qty)包含为[AvgSellPrice]时,它会给我这个错误。 问候, prathap。

2 个答案:

答案 0 :(得分:0)

一旦您正确格式化了代码,就很容易发现错误:

sum(b.SellPrice) SellPrice

sum(b.SellPrice) AS SellPrice

答案 1 :(得分:0)

感谢您的建议。我已经更改了SP,如果它工作正常,虽然我很惊讶为什么它的工作。这类似于我的问题中发布的一个小改动 **

Alter proc [dbo].[SD_GetProfitibilityPerItemDetails] 
@fromdate datetime,
@todate datetime 
as  
Begin 

with p as (
select b.ItemCode,b.ItemDesc as [Description],  
sum(c.BatchSellQty) as Quantity,(sum(b.SellPrice)/sum(c.BatchSellQty)) as AvgSellPrice,
(sum(b.NetPrice)/sum(c.BatchSellQty)) as AvgNetPrice

from 
InvoiceDetails a inner join ItemDetails b on a.QuoteID=b.QuoteID  
inner join BatchDetails c on  b.QuoteID=c.QuoteID and b.ItemID=c.ItemID   
where b.IsDeleted=0  and a.InvoiceDate between @fromdate and @todate
group by b.ItemCode,b.ItemDesc)  
select p.ItemCode,p.Description,p.Quantity,p.AvgNetPrice  as [Avg Net Price],
**AvgSellPrice as [Avg Sell Price],**
(p.AvgSellPrice - p.AvgNetPrice) as [ProfitAmount]

from p

End

在此SP中,当我包含P(p.AvgSellPrice为[Avg Sell Price])时,它给了我一个错误。但当我删除P(AvgSellPrice为[Avg Sell Price])时,它就像一个魅力,虽然它是奇怪。