use isdate function like ..
(CASE WHEN ISDATE (invoice_date) = 1
THEN convert(datetime, cast([invoice_date] as char(8)))
END) AS Invoice_Date
Frage
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.
Lösung
use isdate function like ..
(CASE WHEN ISDATE (invoice_date) = 1
THEN convert(datetime, cast([invoice_date] as char(8)))
END) AS Invoice_Date
Andere Tipps
You can use the ISDATE function, but what would do for non-date values? In my suggested solution you can choose to return a null:
select
(case
when ISDATE (invoice_date)=1
then convert(datetime, invoice_date)
else null end) AS Invoice_Date
from your_table
ISDATE
Returns 1 if the expression is a valid date, time, or datetime value; otherwise, 0. ISDATE returns 0 if the expression is a datetime2 value.
You can go with TRY
CATCH
DECLARE @Source char(8)
DECLARE @Destination datetime
set @Source='07152009'
BEGIN TRY
SET @Destination=CONVERT(datetime,RIGHT(@Source,4) -- YYYY
+LEFT(@Source,2) -- MM
+SUBSTRING(@Source,3,2) -- DD
)
END TRY
BEGIN CATCH
PRINT 'ERROR!!!'
END CATCH
SELECT @Source AS Source, @Destination AS Destination