Selecting most recent date between two columns

前端 未结 13 1407
再見小時候
再見小時候 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:02

    AFAIK, there is no built-in function to get the maximum of two values, but you can write your own easily as:

    CREATE FUNCTION dbo.GetMaximumDate(@date1 DATETIME, @date2 DATETIME)
    RETURNS DATETIME
    AS
    BEGIN
        IF (@date1 > @date2)
            RETURN @date1
        RETURN @date2
    END
    

    and call it as

    SELECT Id, dbo.GetMaximumDate(Date1, Date2)
    FROM tableName
    

提交回复
热议问题