Home >> FAQs/Tutorials >> SQL Server FAQ

SQL Server FAQ - "IF ... ELSE IF ... ELSE ..." Statement Structures

By: FYIcenter.com

(Continued from previous topic...)

How To Use "IF ... ELSE IF ... ELSE ..." Statement Structures?

"IF ... ELSE IF ... ELSE ..." statement structure is used to select one of the specified statements to be executed based on pecified Boolean conditions. Here is the syntax of "IF ... ELSE IF ... ELSE ..." statement structure:

IF condition_1 statement_1;
ELSE IF condition_2 statement_2;
...
ELSE IF condition_n statement_n;
ELSE statement_o;
-- Executes statement_x is 
   if condition_x results in Boolean TRUE 

The tutorial exercise below shows you how to use an IF ... ELSE statement structure to selectively execute one of the CREATE TABLE statements:

USE FyiCenterData
GO

DECLARE @site_name VARCHAR(40);
SET @site_name = 'SQA';
IF @site_name = 'DBA' 
   CREATE TABLE dba_links (url VARCHAR(256));
ELSE IF @site_name = 'SQA' 
   CREATE TABLE sqa_links (url VARCHAR(256));
ELSE
   PRINT 'Unknown site name: '+@site_name;
GO
Command(s) completed successfully.

SELECT name FROM sys.tables WHERE name LIKE '%links';
GO
sqa_links

(Continued on next topic...)

  1. How To Use "IF ... ELSE IF ... ELSE ..." Statement Structures?
  2. How To Use "BEGIN ... END" Statement Structures?
  3. How To Use WHILE Loops?
  4. How To Stop a Loop Early with BREAK Statements?
  5. How To Skip Remaining Statements in a Loop Block Using CONTINUE Statements?

Related Articles:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...