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
Answered by:- jaiprakash
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
https://qawithexperts.com/article/sql/understanding-sql-server-switch-case-with-example/147
I hope this helps, thanks
Answered by:- vikas_jk
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:
CASE statement checks each row to see if the conditional statement—year = 'SR' is true.
is_a_senior.
is_a_senior column.
player_name and year columns.
Refer these websites:
1.
https://community.modeanalytics.com/sql/tutorial/sql-case/
2.https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql
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.
Answered by:- pika
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