SQL date conversion for 8 char value with 00 as days
-
21-06-2021 - |
Question
I have been having trouble trying to figure out how to properly convert the data. In its current form it is varchar and the data is as follows:
19260200, 19770900, 20030400, 20120300, 20020500,
So as you can see I have the year and months, but have no values for dates. When I try to insert it into SQL field formatted as datetime i get errors. Anyone know how i can fix this? I am working with a DB of 700,000 records so I need to be able to write some code to address it and not just manually go through and change.
Thanks in advance for the help!!!
Solution
INSERT dbo.destination(date_column)
SELECT dt FROM
(
SELECT dt = CASE
WHEN src_date_column LIKE '%00' THEN
STUFF(src_date_column, 8, 1, '1')
ELSE src_date_column
END
FROM dbo.source
) AS x
WHERE ISDATE(dt) = 1;
To address comments:
AS x
is just an alias. A derived table needs to be called something. If you just say:
SELECT x FROM (SELECT x = 1);
You get this unhelpful error:
Msg 102, Level 15, State 1
Incorrect syntax near ';'.
But not if you say:
SELECT x FROM (SELECT x = 1) AS y;
As for your other question, you can simply add other columns to the inner SELECT
, e.g.:
INSERT dbo.Citation(PatentNo, Citation, CitedBy, CitationDate)
SELECT PatentNo, Citation, WhoCitedThis, dt
FROM
(
SELECT PatentNo, CitationSource, WhoCitedThis, dt = CASE
WHEN CitationDate LIKE '%00' THEN STUFF(CitationDate, 8, 1, '1')
ELSE CitationDate
END
FROM dbo.CitationSource
) AS x
WHERE ISDATE(dt) = 1;
Now, you need to decide what you want to do with invalid dates, such as 20120231 or 20120399. Those are just left behind. My first recommendation would be to make that a proper date or datetime column, and reject bad dates from getting into the system in the first place.
OTHER TIPS
You can try something like this:
cast(left(val, 6)+'01') as date)
That is, insert a valid day value into the string and do the conversion.