Skip to content

Instantly share code, notes, and snippets.

@FilipDeVos
Created August 2, 2012 09:09
Show Gist options
  • Save FilipDeVos/3235674 to your computer and use it in GitHub Desktop.
Save FilipDeVos/3235674 to your computer and use it in GitHub Desktop.
Performance of scalar functions is usually not very good, to do what you ask I would write it as a table valued function. A table valued function has the benefit that it is inlined properly.
Other forms of the query will not make a huge difference as it is the calls to the function which eat up the time.
CREATE FUNCTION dbo.fn_age(@birthdate datetime, @current_date datetime)
RETURNS TABLE
WITH SCHEMABINDING
AS
return (
SELECT cast((DATEPART(year, @current_date - @birthdate)) - 1900 as varchar(4)) + 'y '
+ cast(DATEPART(month, @current_date - @birthdate) as varchar(2)) + 'm'
+ cast(DATEPART(day, @current_date - @birthdate) as varchar(2)) + 'd' as [Age]
)
GO
This function has to be called like this:
SELECT Age = (SELECT Age FROM dbo.fn_age(birthDate, current_timestamp))
FROM Person
Comparison with other alternatives
==================================
When writing this problem as a normal scalar function I would create something like this:
CREATE FUNCTION dbo.fn_age_slow(@birthdate datetime, @current_date datetime )
RETURNS VARCHAR(10)
WITH SCHEMABINDING
AS
begin
return cast((DATEPART(year, @current_date - @birthdate) - 1900) as varchar(4)) + 'y '
+ cast(DATEPART(month, @current_date - @birthdate) as varchar(2)) + 'm'
+ cast(DATEPART(day, @current_date - @birthdate) as varchar(2)) + 'd'
end
GO
As you can see it does exactly the same as the table valued function. (it is also schema bound which makes the functions faster in some cases)
When running the following script against the first function (on my pc)
declare @a varchar(10) = ''
, @d datetime = '20120101'
, @i int = 1
, @begin datetime
select @begin = CURRENT_TIMESTAMP
while @i < 1000000
begin
select @a = Age
, @d = @begin - @i%1000
, @i += 1
from dbo.fn_age5(@d, @begin)
end
select CURRENT_TIMESTAMP - @begin
GO
**==> 00:00:04.703**
declare @a varchar(10) = ''
, @d datetime = '19500101'
, @i int = 1
, @begin datetime
select @begin = CURRENT_TIMESTAMP
while @i < 1000000
begin
select @a = dbo.fn_age_slow(@d, @begin)
, @d = @begin - @i%1000
, @i += 1
end
select CURRENT_TIMESTAMP - @begin
**==> 00:00:10.310**
This is in no way a proper benchmark but it should give you an idea about the performance difference.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment