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_expression
is a logical expression that is returned if true, true_value
otherwise false_value
.
Here are some IIF
examples 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 IIF
functions were only introduced in SQL Server 2012 and above. In earlier versions, CASE
a statement could be used to achieve similar functionality. Also, IIF
the functions are not standard SQL functions and may not be supported in other database management systems.