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
 Do you need ELSE IF?

Author  Topic 

MMMY
Starting Member

14 Posts

Posted - 2012-08-23 : 13:28:24
Here is a sample code

IF COLOR = 'BLUE'
BEGIN
SET COLOR = 'RED'
END
IF COLOR = 'RED'
BEGIN
SET COLOR = 'YELLOW'
END

So if I pass a value that is blue, will the result be RED or YELLOW? I am trying to understand a script I inherited where I only want COLOR to change based on the ORIGINAL. So if it's BLUE, I want it to become RED, not YELLOW.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-08-23 : 13:51:37
You would need ELSE as in:
IF @COLOR = 'BLUE'
BEGIN
SET @COLOR = 'RED'
END

ELSE IF @COLOR = 'RED'
BEGIN
SET @COLOR = 'YELLOW'
END
An alternate way that I like better is using a CASE expression:
SET @COLOR = 
CASE
WHEN @color = 'BLUE' THEN 'RED'
WHEN @color = 'RED' THEN 'YELLOW'
ELSE @color
END
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-23 : 14:10:25
you can also use simple case structure here

CASE @Color
WHEN 'BLUE' THEN 'RED'
WHEN 'RED' THEN 'YELLOW'
ELSE @Color
END




------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -