IsDate Function in SQL evaluates invalid dates as valid

后端 未结 3 1033
逝去的感伤
逝去的感伤 2020-12-13 21:54

I am running a SQL Statement against imported data from Excel Files. In this SQL I am checking if the users have entered dates properly by using IsDate function. Since this

相关标签:
3条回答
  • 2020-12-13 22:09

    maybe just check dt's LEN? however, it can not handle cases when the len is valid. maybe input validation should happen in the frontend?

    0 讨论(0)
  • 2020-12-13 22:15

    Try setting the dateformat first - that worked for me when I was seeing exceptions.

    set dateformat dmy
    select IsDate(<column>)
    from Table
    
    0 讨论(0)
  • 2020-12-13 22:25

    I do a lot of data conversion work and here is a function that I created and use it practically everyday to weed out the bad dates:

    CREATE FUNCTION dbo.fnCheckDate
    (@InDate nvarchar(50))
    RETURNS DATETIME
    AS
        BEGIN
            declare @Return DATETIME
    
            select @return = CASE WHEN ISDATE(@InDate) = 1
                                THEN CASE WHEN CAST(@InDate as DATETIME) BETWEEN '1/1/1901 12:00:00 AM' AND '6/6/2079 12:00:00 AM'
                                        THEN @InDate
                                        ELSE null
                                        END
                                ELSE null
                                END
            return @return
        END
    GO
    

    Results:

    SELECT dbo.fnCheckDate('07/001/2012') --> Returns 2012-07-01 00:00:00.000
    SELECT dbo.fnCheckDate('2012-07-002') --> Returns 2012-07-01 00:00:00.000
    SELECT dbo.fnCheckDate('007/002/2012') --> Returns 2012-07-01 00:00:00.000
    SELECT dbo.fnCheckDate('00/002/2012') --> Returns Null
    SELECT dbo.fnCheckDate('006/031/2012') --> Returns Null
    SELECT dbo.fnCheckDate('') --> Returns Null
    
    0 讨论(0)
提交回复
热议问题