Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

I need to branch my T-SQL stored procedure (MS SQL 2008) control flow to a number of directions:

CREATE PROCEDURE [fooBar]    @inputParam INT AS BEGIN   IF @inputParam = 1   BEGIN     ...   END   ELSE IF @inputParam = 3   BEGIN     ...   END   ELSE IF @inputParam = 3   BEGIN     ...   END END 

Is there any other ways? For example, in C# I shoud use switch-case block.

like image 717
abatishchev Avatar asked Oct 13 '09 18:10

abatishchev


People also ask

Which is similar to if/then else in SQL?

The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

Can we use IF ELSE in stored procedure?

The IF ELSE statement controls the flow of execution in SQL Server. It can be used in stored-procedures, functions, triggers, etc. to execute the SQL statements based on the specified conditions.

How do you handle IF ELSE in SQL?

The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces another Transact-SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE.


1 Answers

IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!

like image 61
Philip Kelley Avatar answered Sep 30 '22 07:09

Philip Kelley