Sunday, February 12, 2012

Are there MIN(A,B) or MAX(A,B) functions in SQL?

Just wondering, since I came across a case where I have to select the MIN of 2 dates, or MAX of 2 dates

say I want

min_date = MIN(dateA, dateB)

max_date = MAX(dateA, dateB)

I can probably do it with CASE statement, but that seems a bit clumsy

like min_date = CASE WHEN dateA < dateB THEN dateA ELSE dateB END

Thanks

If I were you, I would write a function that returns the min or max of the two and call that function in your statement. Like this:

create function dbo.udf_maxdate
(
@.date1 datetime,
@.date2 datetime
)
returns datetime
as
begin
declare @.returndate datetime
set @.returndate = case when @.date1>@.date2 then @.date1 else @.date2 end
return(@.returndate)
end|||

Unfortunately, no.

You could create your own. Perhaps passing in an array of values (as a string/varchar). Then using something like Jen Suessmeyer's Split function, move the array values into a table variable, use Min() or Max() and return the appropriate value.

Split Function (Jens Suessmeyer)
http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=419984&SiteID=17
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=326300&SiteID=1

|||

Thanks guys

I just used CASE statements, good enough for the one-time fix

No comments:

Post a Comment