IF ... ELSE Statement in SQL Server Transact-SQL

Q

How to execute statements under given conditions in SQL Server Transact-SQL? How to use IF ... ELSE statements?

✍: FYIcenter.com

A

You can use IF ... ELSE statements to execute statements under given conditions in Transact-SQL using these syntaxes:

IF condition statement_1

IF condition statement_1
ELSE statement_2

IF condition 
   -- statement_block_1
   BEGIN
      ... statements ...
   END

IF condition
   -- statement_block_1
   BEGIN
      ... statements ...
   END
ELSE
   -- statement_block_2
   BEGIN
      ... statements ...
   END

When a IF...ELSE statement is executed, the system will:

  • Evaluate the "condition" and decide what to do next.
  • If the result of the "condition" is true, the statement_1 or statement_block_1 is executed.
  • If the result of the "condition" is false, the statement_2 or statement_block_2 is executed unless it is not provided.

Here is an example on how to use IF ... ELSE conditional statements:

IF DATENAME(weekday, GETDATE()) IN ('Saturday', 'Sunday') 
   BEGIN
      PRINT 'It''s a weekend.';
      PRINT 'You can stay home.';
   END 
ELSE 
   BEGIN
      PRINT 'It''s a weekday.';
      PRINT 'You need to go to work.';
   END

 

Conditional Statements and Loops in SQL Server in SQL Server Transact-SQL

⇒⇒SQL Server Transact-SQL Tutorials

2017-01-11, 310👍, 0💬