Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find invalid dates in SQL Server 2008

I have a 300.000 rows table; one of the columns is a varchar() but it really contains a date xx/xx/xxxx or x/x/xxxx or similar. But executing the following test yields an error:

SELECT CAST(MyDate as Datetime) FROM MyTable

The problem is that it doesn’t tell me in which row…

I have executed a series of “manual” updates by trial an error and performed simple updates to fix those, but there’s got to be some weird values that need to either be deleted or fixed.

For example I performed a simple test that fixed about 40 rows:

UPDATE MyTable SET MyDate = REPLACE(MyDate, '/000','/200') FROM MyTable WHERE MyDate like ('%/000%’)
UPDATE MyTable SET MyDate = REPLACE(MyDate, '/190','/199') FROM MyTable WHERE MyDate like ('%/190%’)

This fixed quite a few weird rows that had dates like 01/01/0003 and such. (Dates range from 1998 to 2010).

However, I’d like to know which rows are failing in the above select.

What would be the best way to print those so I can either delete them, edit them or see what to do? Thanks.

like image 844
Martin Marconcini Avatar asked Jun 17 '10 10:06

Martin Marconcini


People also ask

How do I find an invalid 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 ).

How check date format is correct or not 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 SQL?

ISDATE will return 0 if the expression is a datetime2 value, but will return 1 if the expression is a valid datetime value. 0. Any value that mixes a valid date with an invalid value, for example 1995-10-1a. 0.


3 Answers

SELECT
    *
FROM
   MyTable
WHERE
    ISDATE(MyDate) = 0
like image 91
Robin Day Avatar answered Sep 21 '22 19:09

Robin Day


Did you try the ISDATE function?

like image 38
Jakob Christensen Avatar answered Sep 23 '22 19:09

Jakob Christensen


Careful with IsDate. I have 1 bad record in a table of thousands. It says 8201-11-30 is a valid date. IsDate should have a YEAR limitation.

like image 45
John Waclawski Avatar answered Sep 21 '22 19:09

John Waclawski