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.
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 ).
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).
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.
SELECT
*
FROM
MyTable
WHERE
ISDATE(MyDate) = 0
Did you try the ISDATE
function?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With