Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function like isdate() for datetime2?

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?

like image 258
Vladimir Avatar asked Jun 15 '12 02:06

Vladimir


People also ask

Is there an Isdate function?

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.

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 value is a date 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).

Is Datetime2 better than datetime?

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.


1 Answers

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 Docs
TRY_PARSE documentation on Microsoft Docs

like image 62
Aaron Bertrand Avatar answered Sep 18 '22 17:09

Aaron Bertrand