1

I have a TVF which needs 2 parameters a countrycode which is fixed within my general select statement

DECLARE @CountryCode as nvarchar(2)
SET @CountryCode = 'GB'

and a Date of which there will be many in my Select statement result

My TVF needs to pick up the Countrycode and date at runtime - if that's possible!

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 

I have tried to write my calling code as a left join like this

left join V3_PriceList_Country_lvl(@CountryCode, a.[Week_ending]) pl on pl.SKU = a.UID

but I get the following error message

The multi-part identifier "a.Week_ending" could not be bound.

If I could fix the date into a Declare variable it would work but the date will change on every row for every country and SKU. Apart from a regular Left join to the full V3_PriceList table how can make this work?

1 Answer 1

2

You need to use OUTER APPLY, no left join.

If you want to pass a value from outer table to your UDF as parameter, use CROSS APPLY/OUTER APPLY instead of INNER JOIN/OUTER JOIN.

Sample:-

SELECT ...
FROM [table_name] AS a
OUTER APPLY V3_PriceList_Country_lvl(@CountryCode, a.[Week_ending]) pl
WHERE ...

More info here...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks after a bit of faffing about I also found that it needs to go after all of the other left joins. Read up on the APPLY function here which explains it quite well mssqltips.com/sqlservertip/1958/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.