| Subcribe via RSS

Switch Case in SQL

March 31st, 2007 Posted in Programming


Usually when designing a database I often use an integer to save values that represent a string. To make it clear see table below:

Name

Role ID

Markus

1

Jose

2

Anonymous

3

On the table above I use integers to represent role id names, 1 = ‘Administrator’, 2 = ‘User’, 3 = ‘Guest’.

Because I use an integer as the role id, then on the application interface that I make, I need to convert it to a string ‘Administrator’ or ‘User’ or ‘Guest’. This can be done with a simple if else statement like the one below:

If (role == 1)
{
roleName = ‘Administrator’;
}
Else if (role == 2)
{
roleName = ‘User’;
}
Else
{
roleName = ‘Guest’;
}

Instead of using if else statement on the code, we can use SQL command that will do the same thing. To do this ‘if else’ command we can use ELT(N,str1,str2,str3,…) SQL command. ELT will return str1 if N = 1, str2 if N = 2, and so on. Here is the example of using ELT:

SELECT Name, ELT(RoleID, ‘Administrator’, ‘User’, ‘Anonymous’) AS Role FROM User;

The output data that we will get is like in the table below:

Name

Role

Markus

Administrator

Jose

User

Anonymous

Anonymous

The benefit of using ELT() is that we can make the data ready for presentation in the application interface without the need to make an if else code.

Markus

Most Commented Posts

4 Responses to “Switch Case in SQL”

  1. Willy Sudiarto Raharjo Says:

    I bet you got this when you work on EPM :D


  2. johan Says:

    Quite nice, but what happens if roleID starts -for example- at 4? Or you want to start it at 4, because you do not need the 1,2,3? Can you exend the ELT() statement with that?


  3. Markus Says:

    i think it can’t, ELT() always start from 1. but of course you can set an empty string for 1,2,3 and start on 4th


  4. johan Says:

    Or maybe you can use the where clause “RoleID > 3″
    Maybe this can work?


Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word