If I have a table that (among other columns) has two DATETIME columns, how would I select the most recent date from those two columns.
Example:
You can throw this into a scalar function, which makes handling nulls a little easier. Obviously it isn't going to be any faster than the inline case statement.
ALTER FUNCTION [fnGetMaxDateTime] (
@dtDate1 DATETIME,
@dtDate2 DATETIME
) RETURNS DATETIME AS
BEGIN
DECLARE @dtReturn DATETIME;
-- If either are NULL, then return NULL as cannot be determined.
IF (@dtDate1 IS NULL) OR (@dtDate2 IS NULL)
SET @dtReturn = NULL;
IF (@dtDate1 > @dtDate2)
SET @dtReturn = @dtDate1;
ELSE
SET @dtReturn = @dtDate2;
RETURN @dtReturn;
END