I know there is a function called ISDATE
to validate DATETIME
columns, but it works only for the SMALLDATETIME
and DATETIME
types.
Is there a similar way to validate the new data type DATETIME2
in SQL Server 2008 and 2012?
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.
The ISDATE() function checks an expression and returns 1 if it is a valid date, otherwise 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).
Microsoft recommends using DateTime2 instead of DateTime as it is more portable and provides more seconds precision. Also, DateTime2 has a larger date range and optional user-defined seconds precision with higher accuracy. Datetime2 aligns with SQL standards.
In SQL Server 2012, you can use TRY_CONVERT
:
SELECT TRY_CONVERT(DATETIME2, '2012-02-02 13:42:55.2323623'),
TRY_CONVERT(DATETIME2, '2012-02-31 13:42:55.2323623');
Results:
2012-02-02 13:42:55.2323623 NULL
Or TRY_PARSE
:
SELECT TRY_PARSE('2012-02-02 13:42:55.2323623' AS DATETIME2),
TRY_PARSE('2012-02-31 13:42:55.2323623' AS DATETIME2);
(Same results.)
Sorry that I don't have a clever answer for you for < SQL Server 2012. You could, I guess, say
SELECT ISDATE(LEFT('2012-02-02 13:42:55.2323623', 23));
But that feels dirty.
TRY_CONVERT
documentation on Microsoft DocsTRY_PARSE
documentation on Microsoft Docs
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