SQL SERVER

IIF function in SQL Server

IIF function

  • Introduced in SQL Server 2012
  • Returns one of two the values, depending on whether the Boolean expression evaluates to true or false
  • IIF is a shorthand way for writing a CASE expression

Syntax : IIF ( boolean_expression, true_value, false_value )

Example : Returns Male as the boolean expression evaluates to TRUE

DECLARE @Gender INT SET @Gender = 1 SELECT IIF( @Gender = 1, ‘Male’, ‘Femlae’) AS Gender
Output : 

iif function in sql server example

Example : Using IIF() function with table data. We will use the following Employees table for this example.

sql server iif function example

SQL Script to create Employees table

Create table Employees (      Id int primary key identity,  

    Name nvarchar(10),

     GenderId int )

Go
Insert into Employees values (‘Mark’, 1)

Insert into Employees values (‘John’, 1)

Insert into Employees values (‘Amy’, 2)

Insert into Employees values (‘Ben’, 1)

Insert into Employees values (‘Sara’, 2)

Insert into Employees values (‘David’, 1)

Go
Write a query to display Gender along with employee Name and GenderId. We can achieve this either by using CASE or IIF.

iif function in sql server 2012

Using CASE statement
SELECT Name, GenderId,   

      CASE WHEN GenderId = 1       

                THEN ‘Male’                    

   ELSE ‘Female’                 

  END AS Gender FROM Employees
Using IIF function
SELECT Name, GenderId, IIF(GenderId = 1, ‘Male’, ‘Female’) AS Gender FROM Employees

About the author

shohal

I have profession and personal attachment with custom ERP Software development, Business Analysis, Project Management and Implementation almost (36) ,also Oracle Apex is my all-time favorite platform to developed the software. Moreover i have some website development experience with WordPress. For hand on networking experience DevOps and CCNA, it create me a full package. Here are some core programming language with networking course i have been worked: Oracle SQL ,PL/SQL,Oracle 19c Database , Oracle Apex 20.1,WordPress,Asp.Net ,MS SQL ,CCNA ,Dev Ops, SAP SD

Leave a Comment