문제

Below is the Stored Procedure using Common table expression.But i keep on getting Invalid Column name 'SellPrice'.Can you please let me know where am i going wrong

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

** Interestingly when I remove this "(SellPrice/Qty) as [AvgSellPrice]" it works good.But when I include the (SellPrice/Qty) as [AvgSellPrice] it gives me that error. Regards, prathap.

도움이 되었습니까?

해결책

Thanks for your suggestions.I have changed the SP as below and it works fine, though i am surprised why its working.This is similar to the one posted in my question with a minor change **

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

In this SP when i include P (p.AvgSellPrice as [Avg Sell Price]) it gives me a error.But when I removed P (AvgSellPrice as [Avg Sell Price]) it works like a charm,though it is strange.

다른 팁

Once you've properly formatted your code the mistake is easy to find:

turn

sum(b.SellPrice) SellPrice

into

sum(b.SellPrice) AS SellPrice
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top