SQL Server function to return minimum date (January 1, 1753)

前端 未结 8 657
生来不讨喜
生来不讨喜 2021-02-01 11:43

I am looking for a SQL Server function to return the minimum value for datetime, namely January 1, 1753. I\'d rather not hardcode that date value into my script.

Does an

8条回答
  •  星月不相逢
    2021-02-01 12:04

    Here is a fast and highly readable way to get the min date value

    Note: This is a Deterministic Function, so to improve performance further we might as well apply WITH SCHEMABINDING to the return value.

    Create a function

    CREATE FUNCTION MinDate()
    RETURNS DATETIME WITH SCHEMABINDING
    AS
    BEGIN
        RETURN CONVERT(DATETIME, -53690)
    
    END
    

    Call the function

    dbo.MinDate()
    

    Example 1

    PRINT dbo.MinDate()
    

    Example 2

    PRINT 'The minimimum date allowed in an SQL database is ' + CONVERT(VARCHAR(MAX), dbo.MinDate())
    

    Example 3

    SELECT * FROM Table WHERE DateValue > dbo.MinDate()
    

    Example 4

    SELECT dbo.MinDate() AS MinDate
    

    Example 5

    DECLARE @MinDate AS DATETIME = dbo.MinDate()
    
    SELECT @MinDate AS MinDate
    

提交回复
热议问题