As easily we use the if else statement in stored procedure to check the statement type and there after we perform the desired task. Same thing I want to do using switch case
There is no stored procedure posted in the above question description so considering this, your stored procedure can be
Create Proc Usp_SampleProcedure ( @InParam Int )As Begin Set Nocount On Select Case @InParam When 1 Then 'One' When 2 Then 'Two' When 3 Then 'Three' Else '...' End [Result] End Go
But I would like to advise., sql Case can be applied to one column and you can't put a query/statement within both "then" and "else" clause, Consider reading these article
I hope this helps, thanks
Here is the more explanation on SQL SWITCH case expression, Syntax for a simple Switch case statement is
CASE expression WHEN data1 THEN output1 WHEN data2 THEN output1 . . . WHEN dataN THEN outputN ELSE defaultStatement
Not only we can have an expression in SWITCH CASE but also a series of a boolean expression. See the sample below
CASE WHEN boolExpression1 THEN output1 WHEN boolExpression2 THEN output1 . . WHEN boolExpressionN THEN outputN ELSE defaultStatement
Example of the CASE statement
SELECT player_name, year, CASE WHEN year = 'SR' THEN 'yes' ELSE NULL END AS is_a_senior FROM benn.college_football_players
here’s the explanation of above example:
CASEstatement checks each row to see if the conditional statement—
year = 'SR'is true.
Here is the article based on SQL server stored procedure Understanding SQL server switch case (With Example) you can read it, it has all the details.
Switch case simple example in SQL Server
SELECT CASE WHEN x1=1 THEN (SELECT id FROM someTable) ELSE (SELECT id FROM otherTable)
Above code get id from table "someTable" if x1 = 1, else from table "otherTable'.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly