Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsDate Function in SQL evaluates invalid dates as valid

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 is a raw data that hasn't been converted yet, all dates are stored in a varchar data type field.

In some circumstances IsDate returns 1 (valid date) when there is clearly an incorrect date format entered by the user.

For Example:

07/001/2012

2012-07-002

007/002/2012

Any Suggestions on how to handle this problem?

SELECT *
  FROM tblImport
 WHERE (ISDATE(dt) = 0 
        AND (dt is not null AND dt <> ''))

Thanks!

p.s. Smacking users' did not help.

like image 362
ssokol91 Avatar asked Jul 31 '12 17:07

ssokol91


People also ask

What is Isdate function in SQL?

The ISDATE() function checks an expression and returns 1 if it is a valid date, otherwise 0.

How do you check if a date format is valid in SQL?

SQL has IsDate() function which is used to check the passed value is date or not of specified format, it returns 1(true) when the specified value is date otherwise it return 0(false).

What is Isdate function in Excel?

Returns a Boolean value indicating whether an expression can be converted to a date. The required expressionargument is a Variant containing a date expression or string expression recognizable as a date or time.

How do I get the wrong date in SQL?

In SQL Server, you can use the ISDATE() function to check if a value is a valid date. To be more specific, this function only checks whether the value is a valid date, time, or datetime value, but not a datetime2 value. If you provide a datetime2 value, ISDATE() will tell you it's not a date (it will return 0 ).


1 Answers

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
like image 79
Mark Kram Avatar answered Sep 19 '22 15:09

Mark Kram