Check if value is date and convert it

Inus C picture Inus C · May 3, 2013 · Viewed 60.3k times · Source

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.

Answer

Deniyal Tandel picture Deniyal Tandel · May 3, 2013

use isdate function like ..

  (CASE WHEN ISDATE (invoice_date) = 1 
             THEN convert(datetime, cast([invoice_date] as char(8)))
             END) AS Invoice_Date