Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 create a new column in a select statement

Author  Topic 

mcinvalek
Starting Member

5 Posts

Posted - 2014-05-28 : 12:33:30
I am trying to create a new column 'COL_4' and, in the same step, create a case statement off of the new col. I know that the code below will not execute. I realize that I could get ride of COL_4 in my code below and concatonate but I need to keep Col_4 in the output. Any advise?


SELECT
COL_1
,COL_2
,COL_3
,COL_4 = COL_1 + COL_2
,COL_5 = CASE
WHEN COL_1
THEN 'SOMETHING'
END

FROM TABLE_1
;

_keith

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2014-05-28 : 12:38:40
You can use a derived table or you need to repeat the logic to create COL_4:
SELECT 
COL_1
,COL_2
,COL_3
,COL_4
,COL_5 = CASE
WHEN COL_4
THEN 'SOMETHING'
END
FROM
(
SELECT
COL_1
,COL_2
,COL_3
,COL_4 = COL_1 + COL_2
FROM TABLE_1
) AS A

-- OR


SELECT
COL_1
,COL_2
,COL_3
,COL_4 = COL_1 + COL_2
,COL_5 = CASE
WHEN COL_1 + COL_2
THEN 'SOMETHING'
END

FROM TABLE_1
Go to Top of Page
   

- Advertisement -