I want to create a function similar to DATEDIFF in MS SQL Server 2008 R2. The first parameter in DATEDIFF is a datepart. Can I use datepart as a parameter in my function? If not, how do I create a parameter similar to datepart? I don't want to make the parameter text.
For example, I would like to have a function like this: MYFUNC(datepart, timestart, timeend)
So when I call the function, it would look like this: MYFUNC(Hour, N'08:00:00', N'12:00:00')
I'm currently using a nvarchar for the datepart param so my function looks like this: MYFUNC(N'Hour', N'08:00:00', N'12:00:00')
1 Answer 1
You can't do what Microsoft does with built-ins, sorry. You will need to write your function to accept a string, for example, and evaluate it inline, e.g.
CREATE FUNCTION dbo.CustomDateDiff
(
@datepart VARCHAR(32), -- does not need to be NVARCHAR
@start DATETIME,
@end DATETIME
)
RETURNS INT
AS
BEGIN
RETURN (SELECT CASE @datepart
WHEN 'HOUR' THEN DATEDIFF(HOUR, @start, @end)
WHEN 'MINUTE' THEN DATEDIFF(MINUTE, @start, @end)
WHEN 'WEEK' THEN DATEDIFF(WEEK, @start, @end)
ELSE DATEDIFF(DAY, @start, @end)
END);
END
GO
Not that you can't use a conditional inside DATEDIFF
- a lot of people think you could say:
DATEDIFF(@datepart,
Or
DATEDIFF(CASE WHEN @datepart = 'HOUR' THEN HOUR END,
But neither of these will work - both yield:
Msg 1023, Level 15, State 1, Line 2
Invalid parameter 1 specified for datediff.
-
How would you be able to duplicate Microsoft's built-ins? Do you have to use the CLR functionality? Or is it exclusive to Microsoft?Icono123– Icono1232012年11月27日 18:02:19 +00:00Commented Nov 27, 2012 at 18:02
-
1You'd have to have access to SQL Server source code and make adjustments there. Any CLR functionality you write still can only accept proper SQL Server data types... never mind that
DATEDIFF
won't be able to use the variable you pass in anyway.Aaron Bertrand– Aaron Bertrand2012年11月27日 18:04:19 +00:00Commented Nov 27, 2012 at 18:04
HOUR
as a parameter - you need to pass a value that conforms to one of the data types since your parameter must be declared using a data type. Can you explain what you want to do differently fromDATEDIFF
?datediff
.