我有一个TVF需要2个参数国家代码,这些参数在我的一般选择语句中是固定的
DECLARE @CountryCode as nvarchar(2)
SET @CountryCode = 'GB'
和我的Select语句结果中有许多日期
我的TVF需要在运行时获取国家代码和日期 - 如果可能的话!
CREATE function [dbo].[V3_Pricelist_Country_lvl] (@Country as nvarchar(2), @Date as date)
returns table
as
return
SELECT @Country as Country, pl.SKU, pl.[RRP W/O TAX], pl.[BASE PRICE]
FROM V3_PriceList pl
WHERE pl.Country = @Country and @Date between pl.Date and pl.DateEnd and [DISCONTINUED DATE] is null
我曾尝试将我的调用代码编写为左连接,如此
left join V3_PriceList_Country_lvl(@CountryCode, a.[Week_ending]) pl on pl.SKU = a.UID
但是我收到以下错误消息
无法绑定多部分标识符“a.Week_ending”。
如果我可以将日期修改为Declare变量,它会起作用,但日期将在每个国家和SKU的每一行上发生变化。 除了常规的Left连接到完整的V3_PriceList表之外,如何使其工作?
答案 0 :(得分:2)
您需要使用OUTER APPLY
,而不是左连接。
如果要将外表中的值作为参数传递给UDF,请使用CROSS APPLY/OUTER APPLY
代替INNER JOIN/OUTER JOIN
。
样品: -
SELECT ...
FROM [table_name] AS a
OUTER APPLY V3_PriceList_Country_lvl(@CountryCode, a.[Week_ending]) pl
WHERE ...