IF commands ... ELSE in SQL Server

Like other programming languages, SQL Server also provides users with an IF command EL .... The article will detail how to use the syntax and clear examples to make it easier for you to imagine IF ... ELSE.

Like other programming languages, SQL Server also provides users with an IF command EL .The article will detail how to use the syntax and clear examples to make it easier for you to imagine IF . ELSE.

Describe

In SQL Server, the IF statement . ELSE is used to execute conditional instructions, if the correct command executes the command, if it fails it executes another command.

Syntax of using IF . ELSE

To use IF branch statement . ELSE in SQL Server, we use the following syntax:

 IF dieukien 
{. statement executed when condition is TRUE .}

[ELSE
{. the command executes when the condition is FALSE .}]

Note:

  1. ELSE is not required.You will use the ELSE condition when you want to execute a set of statements whose IF condition is evaluated as FALSE (ie, the condition is not met).
  2. There is no ELSE IF condition in the IF . ELSE statement.Instead you must use multiple IF . nested ELSE statements to achieve the desired effect.

IF Structure Diagram . ELSE

Picture 1 of IF commands ... ELSE in SQL Server

Example - IF qualified statement . ELSE

 DECLARE @nhanvien_salary INT; 
SET @nhanvien_salary = 15000000;

IF @nhanvien_salary> 10000000
PRINT 'Truong phong';
ELSE
PRINT 'Graduate';

GO

In the IF statement . This ELSE, if the employee salary> 12000000, the result is given as the Manager, if smaller then the Expert.

Example - The statement has no ELSE conditions

Because the ELSE is not required, this statement may be missing.

 DECLARE @nhanvien_salary INT; 
SET @nhanvien_salary = 15000000;

IF @nhanvien_salary <10000000
PRINT 'Graduate';

GO

In this statement, the program will give the result if the variable @nhanvien_salary

Example - IF statements . nested ELSE

Since we cannot write ELSE IF conditions in SQL Server as in other languages, it is necessary to use multiple IF . nested ELSE statements to achieve the desired effect.

 DECLARE @nhanvien_salary INT; 
SET @nhanvien_salary = 15000000;

IF @nhanvien_salary> 12000000
PRINT 'Detective doc';
ELSE

BEGIN

IF @nhanvien_salary> 10000000
PRINT 'Truong phong';
ELSE
PRINT 'Graduate';

END;

GO

The example given is understood that, if the salary is greater than 12 million, the result will be the Director, otherwise this condition will continue to condition 2, if the salary is greater than 10 million the result will be the Head, Other cases are Specialists.

Previous post: PROCEDURE (Procedure) in SQL Server

Next article: WHILE loop in SQL Server

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile