finding max possible date in ms sql server 2005+

前端 未结 7 1226
名媛妹妹
名媛妹妹 2021-01-01 08:22

Is there a function like GETDATE() in Sql Server 2005 that let\'s you get the max possible date?

I do not want to find the highest date in a table. I wa

7条回答
  •  一个人的身影
    2021-01-01 09:09

    I'm creating a new answer to this question just to address a couple of minor issues with scottm's otherwise good accepted answer.

    1. According to the docs, the maximium value of the time component of a datetime is actually "23:59:59.997", so using a value of "23:59:59.999" will actually round up to midnight the following day. Where the date part is already given as 31st Dec 9999 this would attempt to round up to 1st Jan 10000 which gives an out-of-range error.

    https://msdn.microsoft.com/en-us/library/ms187819(v=sql.105).aspx says:

    Date range: January 1, 1753, through December 31, 9999

    Time range: 00:00:00 through 23:59:59.997

    1. The date literals used are in US format, and while these are not ambiguous for 31st Dec it's best to use ISO format. Nitpicky maybe, but I find reading dates in mm/dd/yyyy format very non-intuitive, and I suspect I'm not alone.

    2. SQL needs the body of the function to be contained in a BEGIN/END block, so as written the example could not be created.

    So my improved version of the max DateTime function is:

    CREATE FUNCTION fnMaxDateTime()
    RETURNS DateTime
    AS
    BEGIN
        RETURN CAST('9999-12-31 23:59:59.997' AS DateTime)
    END
    

提交回复
热议问题