I have a function that gets the Monday of the week @X
weeks in the past/future. I bolted it together from other code on this website. I believe it goes like this:
CREATE FUNCTION [FOO]
(@X INT)
RETURNS DATE
AS
BEGIN
RETURN DATEADD(WEEK, @X, DATEADD(d, -((DATEPART(DW, GETDATE()))
END
I've recently found that if I call this function inside of a view, then I get dramatically worse performance than if I copy and pasted the above code instead. In other words, I find that directly using CAST(DATEADD(WEEK, [X VALUE HERE], DATEADD(d, -((DATEPART(DW, GETDATE())) AS DATE)
to be far more performant than using FOO([X VALUE HERE])
.
If the activity monitor is to be trusted, it's as if the value of GETDATE()
is being forgotten when you use the user-defined function; I see my user-defined function being called a great many times when I try to query any views that use it.
Is there any known cause for this behavior? It's as if making functions with GETDATE()
is always a bad idea. This question hints towards as much, but it's not a direct answer.
I've checked for any type mismatches of any sort. There is none. @@VERSION
reports that I'm on a 2016 version.