I want to create a function which returns a temporary table of dates, for report generation. I want to be able to specify the interval for the table dynamically. Below is a function that encapsulates my problem.
Consider:
CREATE FUNCTION [dbo].[DateAdder]
(@DateStart datetime,
@increment int,
@interval ?????)
Returns datetime
AS
BEGIN
Declare @Return datetime
SELECT @Return = DATEADD(@interval, @increment, @DateStart)
return @Return
END
Is there a way to pass the "Interval" into this function?
(Obviously, I am not trying to rewrite the DATEADD
function, I am just using this as an example to highlight my issue).
Cheers!
You cannot pass a parameter as the interval argument for the DATExxx functions. The easiest thing to do would probably be to pass a varchar, and then duplicate the DATExxx function inside a CASE statement. E.g.:
SELECT @Return = CASE @interval
WHEN 'month' THEN DATEADD(month, @increment, @DateStart)
WHEN 'week' THEN DATEADD(week, @increment, @DateStart)
WHEN 'day' THEN DATEADD(day, @increment, @DateStart)
END
Personal preference - I can never remember the cute abbreviations, I always spell out the intervals in full.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With