Skip to main content

Conditional Statements in SQL Server – IF, ELSE, WHILE,CASE & CHOOSE

 T-SQL, or Transact-SQL, is a procedural programming language used in Microsoft SQL Server. It provides several conditional statements that allow users to create decision-making processes based on specific conditions. These statements include IF...ELSE, CASE, and CHOOSE.

 In this blog, we will explore these conditional statements in T-SQL and their usage.

 IF...ELSE Statement:

 The IF...ELSE statement is used to execute a particular set of SQL statements if a certain condition is true or false. It has the following syntax:

 IF condition

   BEGIN

     -- statement or block of statements executed if condition is true

   END

ELSE

   BEGIN

      -- statement or block of statements executed if condition is false

   END

In this syntax, the condition is a logical expression that evaluates to either true or false. If the condition is true, the statement or block of statements inside the BEGIN and END keywords will be executed. If the condition is false, the statement or block of statements inside the ELSE clause will be executed.

Let's take a look at an example to better understand the usage of the IF-ELSE statement:

DECLARE @number int = 10

IF @number > 0

   BEGIN

      PRINT 'The number is positive'

   END

ELSE

   BEGIN

      PRINT 'The number is negative or zero'

   END

In this example, the condition is @number > 0, which is true since @number is 10. Therefore, the statement inside the BEGIN and END keywords after the IF keyword will be executed, which is to print "The number is positive".

You can also use the IF-ELSE statement with multiple conditions by using the ELSE IF clause. The syntax for the ELSE IF clause is as follows:

IF condition1

   BEGIN

      -- statement or block of statements executed if condition1 is true

   END

ELSE IF condition2

   BEGIN

      -- statement or block of statements executed if condition2 is true

   END

ELSE

   BEGIN

      -- statement or block of statements executed if all conditions are false

   END

Let's take a look at an example that uses the ELSE IF clause:

DECLARE @number int = 0

IF @number > 0

   BEGIN

      PRINT 'The number is positive'

   END

ELSE IF @number < 0

   BEGIN

      PRINT 'The number is negative'

   END

ELSE

   BEGIN

      PRINT 'The number is zero'

   END

In this example, the condition @number > 0 is false since @number is 0. Therefore, the ELSE IF clause will be evaluated, and the condition @number < 0 will also be false. Finally, the ELSE clause will be executed, which prints "The number is zero"

CASE Statement:

The CASE statement is used to create multiple conditions in a single SQL statement. It has two variations: the simple CASE and the searched CASE.

The simple CASE statement has the following syntax:

CASE expression

   WHEN value1 THEN result1

   WHEN value2 THEN result2

   ...

   ELSE resultN

END

Here, expression is the value that we want to evaluate. If it matches any of the valueX, then the corresponding resultX is returned. If none of the values match, then the ELSE block is executed.

For example, consider a table product that contains the details of products and their prices. We can use the CASE statement to categorize the products based on their prices.

SELECT name, price,

   CASE

      WHEN price < 100 THEN 'Low Price'

      WHEN price >= 100 AND price < 500 THEN 'Medium Price'

      ELSE 'High Price'

   END AS price_category

FROM product

 

Here, the CASE statement evaluates the price of each product and categorizes it as Low Price, Medium Price, or High Price.

The searched CASE statement has a similar syntax but uses Boolean expressions instead of values.

CASE

   WHEN boolean_expression1 THEN result1

   WHEN boolean_expression2 THEN result2

   ...

   ELSE resultN

END

CHOOSE Statement:

The CHOOSE statement is used to select a value from a list of expressions based on an index. It has the following syntax:

CHOOSE (index, value1, value2, ..., valueN)

Here, index is the position of the value that we want to select, and valueX is the list of expressions from which we want to select.

For example, consider the following query:

SELECT CHOOSE(2, 'apple', 'banana', 'orange')

Here, the CHOOSE statement selects the value banana as it is in the second position in the list of expressions.

WHILE loop

In SQL Server, the WHILE loop is a control flow statement that allows you to repeatedly execute a block of statements as long as a specific condition is true. It is a powerful feature of T-SQL that is commonly used in various database applications. This blog will cover the usage of the WHILE loop in SQL Server and how it can be used to write effective code.

The syntax for the WHILE loop is as follows:

WHILE condition

   BEGIN

      -- statement or block of statements executed as long as condition is true

   END

 

In this syntax, the condition is a logical expression that evaluates to either true or false. As long as the condition is true, the statement or block of statements inside the BEGIN and END keywords will be executed repeatedly.

Let's take a look at an example to better understand the usage of the WHILE loop:

DECLARE @count int = 1

WHILE @count <= 10

   BEGIN

      PRINT @count

      SET @count = @count + 1

   END

 

In this example, the condition is @count <= 10, which is true since @count is initially 1. Therefore, the statement inside the BEGIN and END keywords after the WHILE keyword will be executed, which is to print the value of @count. The value of @count is then incremented by 1 using the SET statement. The loop will continue to execute as long as @count is less than or equal to 10.

You can also use the WHILE loop with multiple conditions by using the logical operators AND and OR. The syntax for using logical operators in the WHILE loop is as follows:

WHILE condition1 AND/OR condition2 AND/OR condition3

   BEGIN

      -- statement or block of statements executed as long as all conditions are true

   END

Let's take a look at an example that uses logical operators in the WHILE loop:

DECLARE @count int = 1

DECLARE @flag bit = 1

WHILE @count <= 10 AND @flag = 1

   BEGIN

      PRINT @count

      SET @count = @count + 1

    

      IF @count = 6

         SET @flag = 0

   END

 In this example, the WHILE loop executes as long as @count is less than or equal to 10 AND @flag is equal to 1. Inside the loop, the value of @count is printed and incremented by 1 using the SET statement. If @count is equal to 6, the value of @flag is set to 0, which will cause the loop to exit after the current iteration.

Comments

Popular posts from this blog

SFTP Integration in SSIS package Using WinSCP DLL

  In this blog, I am planning to write about SSIS SFTP Task details and reference sites, upload and download the files from SFTP server using SSIS package with help of the winscp library. Steps to configure the winscp DLL and Download Files 1.        Please download the DLL and required files from below path https://winscp.net/eng/downloads.php#additional 2.        Once Downloaded, use the below comments to add in Local GAC "Path to the gacutil exe \gacutil.exe" /i WinSCPnet.dll 3.        Please use the below URL as guide to implement the SSIS script task to download the files from SFTP using winscp as library https://winscp.net/eng/docs/library_ssis 4.        I am just briefing the steps based on the above URL what we can try in SSIS package. 5.        Please create the below variables in SSIS package which we need ...

Geography Data Type – SQL Server

     Geography data type in SQL Server is a useful tool for storing and manipulating geographic data. It provides a set of functions and tools for working with geographical data, such as points, lines, and polygons. In this blog, we will explore the Geography data type in SQL Server with examples. Introduction to Geography data type Geography data type is a built-in data type in SQL Server that is designed to support the storage, manipulation, and analysis of geographic data. It is based on the Open Geospatial Consortium (OGC) Simple Feature Access specification, which provides a standard way to represent geographic data in a database. The Geography data type in SQL Server stores data in a geographic coordinate system, allowing you to represent points on the surface of the earth using longitude and latitude coordinates. You can also represent lines and polygons by defining a series of points that define the shape of the line or polygon. Creating a Geography data t...

XML data type Functions – SQL Server

 The XML data type in MSSQL Server is a powerful tool for handling and manipulating XML data within a relational database system. In addition to storing XML data as a column in a table, SQL Server provides a number of XML functions and methods that allow for easy parsing, querying, and transformation of XML data. In this blog post, we will cover all XML data type methods available in MSSQL Server. value() Method: The value() method is used to extract a single value from an XML instance. This method accepts an XQuery expression as a parameter, which is used to identify the value to be extracted. The syntax of the value() method is as follows: xml . value ( XQuery expression , Data type ) For example, the following query extracts the value of the 'name' element from an XML column called 'MyXMLColumn': SELECT MyXMLColumn . value ( '(/Root/Person/Name)[1]' , 'varchar(50)' ) AS Name FROM MyTable   query() Method: The query() method i...