Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value is date and convert it

I receive data in a certain format. Dates are numeric(8,0). For example 20120101 = YYYYMMDD

There exists rows with values like (0,1,2,3,6) in that date field, thus not a date.

I want to check if it is a date and convert it, else it can be null.

Now the following code works, but I was hoping there is a better way.

(CASE WHEN [invoice_date] LIKE '________' --There are 8 underscores
 THEN convert(datetime, cast([invoice_date] as char(8)))
 END) AS Invoice_Date

Any help will be appreciated.

like image 476
Inus C Avatar asked May 03 '13 07:05

Inus C


People also ask

Is date or not in SQL?

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

How check if value is 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 do I check if a string is in date format?

Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.


1 Answers

use isdate function like ..

  (CASE WHEN ISDATE (invoice_date) = 1 
             THEN convert(datetime, cast([invoice_date] as char(8)))
             END) AS Invoice_Date
like image 108
Deniyal Tandel Avatar answered Sep 21 '22 14:09

Deniyal Tandel