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
关键修改说明:
- 给最后一个
OUTER APPLY的子查询添加了别名cust(你也可以换成customerInfo这类更语义化的名字,只要保持统一就行) - 在SELECT列表里,把原来的
tbl_M_Customer.Customfield1改成了cust.Customfield1,通过别名来引用子查询返回的列
另外补充个小提示:如果每个h.CustomerCode在tbl_M_Customer里可能对应多条记录,记得在子查询里加TOP 1或者用聚合函数(比如MAX(Customfield1)),避免结果集行数意外膨胀。
内容来源于stack exchange
相关产品推荐
相关产品推荐

