Selecting most recent date between two columns

前端 未结 13 1322
再見小時候
再見小時候 2020-12-30 22:15

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:

相关标签:
13条回答
  • 2020-12-30 23:18

    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
    
    0 讨论(0)
提交回复
热议问题