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.