You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server Express中在OUTER APPLY关联函数后添加第三张表并访问其列的语法错误求助

SQL Server Express中在OUTER APPLY关联函数后添加第三张表并访问其列的语法错误求助

看起来你遇到的语法错误是因为最后那个OUTER APPLY里的子查询没有指定别名,SQL Server需要给这个子查询生成的结果集起个名字,这样你才能在SELECT列表里引用它的列。另外,要访问tbl_M_Customer的Customfield1列,你得通过这个别名来调用。

我帮你修正了代码,关键修改点已经标注出来了:

declare @currentweek int 
select @currentweek = datepart(week, getdate()) 

declare @currentyear int 
select @currentyear = datepart(year, getdate()) 

select @currentweek as Current_Week , @currentyear as Current_Year 

SELECT 
    d.DocRef as DocRef,
    h.GRN_Number AS Int_Wbill,
    h.DelNote AS Delivery_Notes,
    h.CustomerCode AS [Producer ID],
    cust.Customfield1 AS GGN, -- 现在通过别名cust访问第三张表的列
    h.CustomerName AS Name,
    h.Run_Date AS [Date],
    DATEPART( WEEK, h.Run_Date ) AS [Week],
    h.CultivarCode AS Commodity,
    h.VarietyCode AS Variety,
    h.Orchard AS [Orchard No],
    h.Containers_Tipped AS TotBins,
    h.Kilograms_Tipped AS TotWeight,
    h.Container_Average AS AvgBinWeight,
    h.BinType AS [Bin Type]
FROM tbl_Doc d 
OUTER APPLY fn_Producer_Packout_Run_HEADER ( d.DocID ) h 
OUTER APPLY ( 
    select Customfield1 
    from tbl_M_Customer 
    where tbl_M_Customer.CustomerCode = h.CustomerCode 
) cust -- 给子查询加别名,这是修复语法错误的核心
WHERE d.DocType = 'PHJ' 
AND DATEPART( WEEK, h.Run_Date ) = @currentweek 
AND DATEPART(YEAR, h.Run_Date ) = @currentyear

关键修改说明:

  1. 给最后一个OUTER APPLY的子查询添加了别名cust(你也可以换成customerInfo这类更语义化的名字,只要保持统一就行)
  2. 在SELECT列表里,把原来的tbl_M_Customer.Customfield1改成了cust.Customfield1,通过别名来引用子查询返回的列

另外补充个小提示:如果每个h.CustomerCode在tbl_M_Customer里可能对应多条记录,记得在子查询里加TOP 1或者用聚合函数(比如MAX(Customfield1)),避免结果集行数意外膨胀。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 09:49:35