Question

in PHP and JavaScript you can use a Switch statement to avoid having multiple if / case statements.

Is there a way to achieve something similar in SQL so that for each case it runs a different Select ? I would not need to cover a default case here, just a number of different case scenarios.

PHP example:

<?php
$myVariableInput;

switch ($myVariableInput) {
   case "input1":
     // do something
     break;
   case "input2":
     // do something different
     break;
   case "input3":
     // do again something different
     break;
}
?>

In my case I would like to have a number of cases and for each of them have a different Select, all within the same stored procedure.

Can someone here tell me if and how this could realised in SQL ?

Many thanks in advance, Tim.

Was it helpful?

Solution

You can either use CASE for simpler actions, or dynamic SQL for more complex query.

CASE can be used from within normal selects / views / table valued functions and would look like:

SELECT CASE WHEN x1=1 THEN (SELECT id FROM someTable) ELSE (SELECT id FROM otherTable)

For using dynamic SQL, you may define the SQL as string, possibly combining with CASE as well. Note this can be used only from within stored procedures:

DECLARE query VARCHAR(max)
SET query = 'SELECT * FROM ' + CASE WHEN @myVariableInput =  THEN 'Table1' ELSE 'Table2' END + ' WHERE some_condition='+@parameterForIt
EXEC sp_executeSql query

However, be aware that this is not usually the best practise, as the database will be confused with different execution plans for different tables. Best practice would be the one you defined in PHP, with different stored procedures for different cases:

switch ($myVariableInput) {
   case "input1":
     // execute StoredProcedure1
     break;
   case "input2":
     // execute StoredProcedure2
     break;
   case "input3":
     // execute StoredProcedure3
     break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top