user6565949 user6565949 - 2 months ago 10
SQL Question

IF ELSE in SQL Server

I have the following column in Microsoft SQL Server called

Type
and I want to create another column called
Type 1
which would be 1 if account starts with letter A, 2 if account starts with D....

I am new with this so could someone please advise?

Type Type 1
AD 1
AV 1
AC 1
DE 2
DR 2
DG 2
KL 3
KL 3

Answer

Use CASE instead of IF:

SELECT 
    Type,
    CASE 
        WHEN Type LIKE 'A%' then 1 
        WHEN Type Like 'D%' THEN 2 
        WHEN ...
    END AS Type1
...
Comments