Sample Header Ad - 728x90

SQL CASE statement ELSE block usage for inserting a record

0 votes
1 answer
106 views
The last line of the following code inserts records from #S to #D if value is a valid date; otherwise it returns NULL (since I am not using ELSE clause): CREATE TABLE #S(COL VARCHAR(15)) INSERT #S VALUES('20250630'),('ABC'),('20150821') CREATE TABLE #E(ERCOL VARCHAR(15)) CREATE TABLE #D(DTCOL DATE) INSERT #D(DTCOL) SELECT (CASE WHEN ISDATE(COL) = 1 THEN (CAST(COL AS DATE)) END) FROM #S **Question**: How can we include ELSE block in the last line of above code and use that block to insert the error value (ABC) into #E table while still using the same SELECT statement as above. So, we are just modifying the last line of the above code: INSERT #D(DTCOL) SELECT (CASE WHEN ISDATE(COL) = 1 THEN (CAST(COL AS DATE)) ELSE 'NEED TO INSERT "ABC" VALUE TO #E TABLE' END) FROM #S
Asked by nam (515 rep)
Jun 30, 2025, 07:57 PM
Last activity: Jul 1, 2025, 07:49 PM