Using MS SQL If Else

Using IF ELSE is an option if you want to run or skip a condition in the query to be written. Using if else in Ms Sql is not much different from other programming languages.

The IF ELSE structure is as follows.

IF {bool expression} BEGIN {expression block} END ELSE BEGIN {expression block} END

In the example below, we assign the value of the month number of the current date to a variable named @MONTH and display 1. We print a value depending on the month or not.

DECLARE @MONTH AS INT SELECT @MONTH = MONTH(GETDATE()) IF @MONTH = 1 BEGIN PRINT 'JANUARY'; END ELSE BEGIN PRINT 'WE ARE IN ANOTHER MONTH'; END

Note: In Ms Sql, IF ELSE is generally used in Stored Procedures, functions and triggers.



You May Interest

Getting List of All Stored Procedures in Database in MS SQL

What is the Use of DBCC Commands in SQL Server ?

What is the XML Datatype in SQL Server ?

What is the Maximum Size per Database for SQL Server Express ?

What is an Index in SQL Server ?