Actually you can do it.
Although, someone should note that repeating the CASE
statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE
twice so that you won't get any performance hit because of that.
Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)
INSERT INTO dbo.T1
(
Col1,
Col2,
Col3
)
SELECT
1,
SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
dbo.T1 t
LEFT OUTER JOIN
(
SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1
This will insert the values (1, 2, 3) for each record in the table T1
. This uses a delimiter '%'
to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar
fields etc.). But the main logic is that you should join the CASE
statement and select from the result set of the join with using a split logic.