In SQL Server, I need to wrap the DATEADD built-in function with another function.
The problem is I need to implement this behaviour:
Return Types
The return data type is the data type of the date argument[…]
For example, if I pass in a datetime as argument, DATEADD returns a datetime. If I pass in a date, DATEADD returns a date.
The following example always returns datetime…
create function add_months(@dt date, @interval int)
returns datetime
as
begin
return DATEADD(month, @interval, @dt)
end
How can I implement this in SQL Server?
(edit)
Context
I’m performing a database migration from informix to SQL Server. The database part is not the issue here, the code is. We have hundreds of programs that must be changed because of the SQL queries embedded in them. This is the main reason I’m trying to avoid to use DATEADD(MONTH, 1, foo). This automatic transformation, while simple in most cases, can be quite difficult in some cases. With a udf I could just replace the name of the informix function and not go into a deeper refactoring.
Overloaded functions aren’t possible. I’m trying to think of a way to shoehorn
SQL_VARIANTinto this but all of the options I can think of lead to unnecessarily disgusting complications. I would make a function that accepts and returns date, and a function that accepts and returns datetime, and call the appropriate one. The ones with lower precision can call the ones with higher so you don’t have to replicate code, e.g.Alternatively, just always use the highest precision (1st function), and worry about whether it’s a date or datetime when you present the data. You can do this with an inline convert or wrapping it in another function appropriately.
EDIT
Or better yet, just replace all calls to this function of questionable value with proper inline dateadd calls.
Becomes:
While it’s not as automatic as you might like, in addition to maintaining your requirement that the output type remains the same as the input, this will also probably improve performance of some queries, depending on where these are used within the query.