Needs Help
Needs Help

Reputation: 121

Case statement in SQL Server 2005

I am not sure what to use in this scenario, but I think a Case statement is apt.

I do not know the syntax however. Can someone please guide me?

I have a variable called @Action which can have about 30 different values.

I want to do something like this

 CASE
 WHEN @Action = 'InsertTbl1' THEN 
  BEGIN
   -- Some Insert statements and one update statements
  END
 WHEN @Action = 'RecalculateCol3' THEN 
  BEGIN
   -- Some update statements
  END
 WHEN @Action = 'Closed' THEN 
  BEGIN
   -- Some delete statements and some update statements

  END
--- and so on.....
 ELSE 
  BEGIN
  END
 END

Upvotes: 4

Views: 7573

Answers (2)

Bryant Bowman
Bryant Bowman

Reputation: 423

Yes, you can use Else If. For example:

declare @temp int
set @temp = 3

if @temp = 1
    print '1'
else if @temp > 1 and @temp < 3
    print '2'
else if @temp >= 3
    print '3'

I would still think about breaking it up into separate procedures as suggested by others

Upvotes: 0

p.campbell
p.campbell

Reputation: 100567

Suggest a structure of IF and ELSE IF to mimic a switch.

IF @MyVar = 'Foo'
BEGIN
    --react to Foo        
END

ELSE IF @MyVar = 'Bar'
BEGIN
    --react to Bar       
END
ELSE
BEGIN
    --default case.
END

Upvotes: 4

Related Questions