【问题标题】:Invalid Column Name while using Common Table Expression使用公用表表达式时列名无效
【发布时间】:2014-03-12 18:42:15
【问题描述】:

以下是使用公用表表达式的存储过程。但我不断收到无效的列名“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) as [AvgSellPrice]”时效果很好。但是当我将 (SellPrice/Qty) 包含为 [AvgSellPrice] 时,它给了我错误。 问候, 普拉塔普。

【问题讨论】:

  • 推测ItemDetails.SellPrice不存在。
  • 调试此类查询的第一步是正确格式化。
  • 已编辑问题。请立即提出建议。

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


【解决方案1】:

感谢您的建议。我已将 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 as [Avg Sell Price]) 时,它给了我一个错误。但是当我删除 P (AvgSellPrice as [Avg Sell Price]) 时,它就像一个魅力,虽然它是奇怪。

【讨论】:

    【解决方案2】:

    正确格式化代码后,很容易发现错误:

    sum(b.SellPrice) SellPrice
    

    进入

    sum(b.SellPrice) AS SellPrice
    

    【讨论】:

    • 嗨 Dalen,我只是忘记在此处编写 SP 时添加“as”。它已经在我的 SP 中了。
    • AS 在这个地方的 SQL Server 中是可选的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2011-06-12
    • 2012-10-22
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多