• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5271
  • Last Modified:

Case statement T-SQL syntax


This works:
SET @X = Case @Y
          WHEN 1 THEN 444
          WHEN 2 THEN 555
END


How can I make this work:
Case @Y
    WHEN 1 THEN
          SET @X =  444
          SET @Z =  222
    WHEN 2 THEN
          SET @X =  555
          SET @Z =  333
END
0
SNilsson
Asked:
SNilsson
  • 2
1 Solution
 
TimCotteeHead of Software ServicesCommented:
Hi SNilsson,

You cannot, the case statement doesn't work that way, you need to use IF..ELSE syntax:

IF @Y = 1
    Begin
        Set @X = 444
        Set @Z = 222
    End
If @Y = 2
    Begin
        Set @X=555
        Set @Z=333
    End

Tim Cottee
Brainbench MVP for Visual Basic
http://www.brainbench.com
0
 
SNilssonAuthor Commented:

Okey, in that case what would be the most efficient, using several If statement or two case statements (Y can hold 7 different valuse so it would be 7 IF's) ?
0
 
TimCotteeHead of Software ServicesCommented:
SNilsson,

50/50 I guess, either way you have 14 sets to do, probably the IFs would be easier to read and maintain.

Tim.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now