I got this code, I would like to optimize.
I basically can add new columns to “Disp” table later on, and I don’t want to come back modify this function.
I cannot use dynamic SQL. Right? Is there anything else that would work in my case?
This is the function:
ALTER FUNCTION [GetDate]
(@hdrnumber INT, @DateColName VARCHAR(50))
RETURNS DATETIME
AS
BEGIN
DECLARE @dt DATETIME
SELECT @dt = CASE
WHEN @DateColName = 'ord_bookdate' THEN [ord_bookdate]
WHEN @DateColName = 'ord_startdate' THEN [ord_startdate]
WHEN @DateColName = 'ord_completiondate' THEN [ord_completiondate]
WHEN @DateColName = 'pack_date_from' THEN [pack_date_from]
WHEN @DateColName = 'pack_date_to' THEN [pack_date_to]
END
FROM [Disp]
WHERE [hdrnumber] = @hdrnumber
RETURN @dt
END
(removed some of the code, because it’s a long one, but hopefully what I left in here will make sense to you guys)
how do i use this function?
well it basically looks like this:
insert into tablename (...)
select somedate, [GetDate](somedate, somecolumn)
from sometable
where 1 = 1
You either need to use dynamic sql which you can’t do within a user-defined function (so you’d need to remove it out of the function), or like you are doing with a CASE statement (which isn’t fully generic).
I think I’d personally go with the CASE approach to start with and consider dynamic sql if proves to give better performance (maybe with a larger number of different possible fields).
You would have some maintenance work to do to keep the CASE up to date, but I can’t imagine more fields would be added that often?