Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Interval parameter to Function in SQL

Tags:

sql-server

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!

like image 565
Molloch Avatar asked Nov 29 '10 08:11

Molloch


1 Answers

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.

like image 200
Damien_The_Unbeliever Avatar answered Sep 23 '22 13:09

Damien_The_Unbeliever