November 29, 2012 at 7:50 am
Hi i'm new here to SQL Server Central and after lurking for a bit it seems like a great community. I'm here because TSQL is a new language for me and i'm reading some material however i would like to ask for some additional help on the following.
I have created a view and i would like to create a column (int) based on the value of a varchar for another field;
example
car = sedan or coupe
new_column = 1 if car = sedan
new_column = 0 if car = coupe
I believe the logic is there but i am just familiarizing myself with the syntax. Note that the purpose of this column is for something outside of SQL.
Thanks
November 29, 2012 at 7:54 am
You can use CASE WHEN:
SELECT ...
,CASE WHEN car = 'sedan' THEN 1
WHEN car = 'coupe' THEN 0
ELSE NULL -- or whatever you think appropriate
END AS [New_Column]
November 29, 2012 at 7:58 am
Hi,
You can do it with a CASE statement. I've included an example below.
DECLARE @Cars TABLE
(
BodyStyle VARCHAR(50)
)
INSERT INTO @Cars
SELECT 'Sedan'
UNION ALL SELECT 'Sedan'
UNION ALL SELECT 'Sedan'
UNION ALL SELECT 'Sedan'
UNION ALL SELECT 'Coupe'
UNION ALL SELECT 'Coupe'
UNION ALL SELECT 'Coupe'
SELECT
*
,CASE
WHEN BodyStyle = 'Sedan' THEN 1
WHEN BodyStyle = 'Coupe' THEN 0
END
FROM
@Cars
November 29, 2012 at 8:10 am
Thank you both Eugene Elutin and s_osborne2! works great!
November 29, 2012 at 8:13 am
No worries, glad it worked.
Thanks,
Simon
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply