Check if value is date and convert it
Asked Answered
T

4

15

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.

Therianthropic answered 3/5, 2013 at 7:2 Comment(0)
B
28

use isdate function like ..

  (CASE WHEN ISDATE (invoice_date) = 1 
             THEN convert(datetime, cast([invoice_date] as char(8)))
             END) AS Invoice_Date
Batavia answered 3/5, 2013 at 7:33 Comment(0)
S
7

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
Slime answered 3/5, 2013 at 7:23 Comment(0)
L
3

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.

Please visit

Linalinacre answered 8/5, 2013 at 11:6 Comment(0)
S
0

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
Steven answered 3/5, 2013 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.