Case statements are obviously a tidy alternative to using simple if/else statements, and I recently found myself in a position where I had a good opportunity to use one.
First off, let’s look at the syntax.
DECLARE @targetVariable INT = CASE @sourceVariable WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 0 END
In the above syntax example, we have the variable @sourceVariable that we are checking, and then setting the variable @targetVariable based on the cases.
Here is a more realistic example, where I am setting a due date for a current payment installment, based on what option the user has chosen.
DECLARE @CurrentInstallmentDueDate DATETIME = CASE @ChoiceID WHEN @Installment1ID THEN @DueDate1 WHEN @Installment2ID THEN @DueDate2 WHEN @Installment3ID THEN @DueDate3 ELSE NULL END
Hope that helps!