tsql - Simple SQL Server queries taking forever when variables/functions are involved -
this i've been struggling while found way around it. have fact table in sql server dw has around 30m records, , integer field called datecreatedkey has non-clustered index on field. have function called dbo.fn_datekeyfromdate
quite simply
declare @ret int = year(@date) * 10000 + month(@date) * 100 + day(@date) return @ret
as see execution times below, if index doesn't work when using function or when using variable. not sure if i'm missing obvious?
now these execution times each of these 5 blocks of code:
a: 0.034s:
select * #subs2 biwarehouse.dbo.factsubscriptions (nolock) datecreatedkey >= 20170814
b: 15.4s:
declare @fromdate int select @fromdate = 20170814 select * #subs3 biwarehouse.dbo.factsubscriptions (nolock) datecreatedkey >= @fromdate
c: 134s:
select * #subs4 biwarehouse.dbo.factsubscriptions (nolock) datecreatedkey >= dbo.fn_datekeyfromdate(getdate()-1)
d: 20s:
declare @fromdate int select @fromdate = dbo.fn_datekeyfromdate(getdate()-1) select * #subs biwarehouse.dbo.factsubscriptions (nolock) datecreatedkey >= @fromdate
i indexes doesn't used when calling function, should work variable. compare execution plans sure.
try if want use function (maybe idea 130s example?):
declare @fromdate int select @fromdate = dbo.fn_datekeyfromdate(getdate()-1) select * #subs biwarehouse.dbo.factsubscriptions (nolock) datecreatedkey >= @fromdate
Comments
Post a Comment