I cannot understand why SQL Server adopts a completely different execution plan when packing my code in ITVF. When executing the code inside ITVF, the request itself is executed after 5 seconds. If I save it as ITVF, it will work for 20 minutes and will not produce a result. I would prefer it to be in ITVF for code reuse. Any ideas why saving code as ITVF could lead to serious performance issues?
CREATE FUNCTION myfunction ( @start_date date, @stop_date date ) RETURNS TABLE AS RETURN ( with ad as ( select [START_DATE] ,[STOP_DATE] ,ID ,NAME ,'domain1\' + lower(DOMAIN1_NAME) collate database_default as ad_name from EMP_INFO where DOMAIN1_NAME != '' union select [START_DATE] ,[STOP_DATE] ,ID ,NAME ,'domain2\' + lower(DOMAIN2_NAME) collate database_default as ad_name from EMP_INFO where DOMAIN2_NAME != '' ) select ad.ID ,ad.NAME ,COUNT(*) as MONITORS from scores join users on (scores.evaluator_id = users.[user_id]) join ad on (lower(users.auth_login) = ad.ad_name and scores.[start_date] between ad.[START_DATE] and ad.[STOP_DATE]) where scores.[start_date] between @start_date and @stop_date group by ad.ID ,ad.NAME )
EDIT:
Well ... I think I understood the problem ... but I do not understand this. Perhaps I should post a completely new question, let me know what you think. The problem here is when I call a function with literals, it is REALLY slow ... when I call it variables, it is fast.
-- Executes in about 3 seconds declare @start_date date = '2012-03-01'; declare @stop_date date = '2012-03-31'; select * from myfunction(@start_date, @stop_date); --Takes forever! Never completes execution... select * from myfunction('2012-03-01', '2012-03-31')
Any ideas?
source share