SQLServer iif function

        SQLServer2012 adds the iif function, which is a logical function that returns one of two possible values ​​based on a condition. Its syntax is as follows:

 

        

IIF ( boolean_expression, true_value, false_value )

        where boolean_expressionis a logical expression that is returned if true, true_valueotherwise false_value.

Here are some IIFexamples of using functions:

        Return whether the age is greater than or equal to 18 years old:

--测试数据
if not object_id(N'Tempdb..#T') is null
	drop table #T
Go
Create table #T([name] nvarchar(22),[age] int)
Insert #T
select N'张三',17 union all
select N'李四',18 union all
select N'王五',19
Go
--测试数据结束
SELECT IIF(age >= 18, '成年人', '未成年人') AS is_adult FROM #T;

        result:

        

        It should be noted that IIFfunctions were only introduced in SQL Server 2012 and above. In earlier versions, CASEa statement could be used to achieve similar functionality. Also, IIFthe functions are not standard SQL functions and may not be supported in other database management systems.

Guess you like

Origin blog.csdn.net/sinat_28984567/article/details/129645578