Usage of IIF in SQL SERVER

290 阅读2分钟

IIF (Transact-SQL)

说明:

返回两个值之一,具体取决于布尔表达式在SQL Server中评估为true还是false。

语法:

IIF ( boolean_expression, true_value, false_value )  

参数

boolean_expression
一个有效的bool表达

true_value
如果boolean_expression评估为true,则返回的值。

false_value
如果boolean_expression评估为false,则返回的值。

返回

从true_value和false_value中的类型返回优先级最高的数据类型。

例子

DECLARE @a int = 45, @b int = 40;  
SELECT IIF ( @a > @b, 'TRUE', 'FALSE' ) AS Result;  
SELECT IIF ( 45 > 30, NULL, NULL ) AS Result;  
DECLARE @P INT = NULL, @S INT = NULL;  
SELECT IIF ( 45 > 30, @p, @s ) AS Result;  

备注

IIF is a shorthand way for writing a CASE expression.  
IIF是编写CASE表达式的简便方法。  
It evaluates the Boolean expression passed as the first argument, and then returns either of the other two arguments based on the result of the evaluation.   
它计算作为第一个参数传递的布尔表达式,然后根据计算结果返回其他两个参数中的一个。  
That is, the true_value is returned if the Boolean expression is true, and the false_value is returned if the Boolean expression is false or unknown. true_value and false_value can be of any type.   
也就是说,如果布尔表达式为true,则返回true_value;如果布尔表达式为false或unknown,则返回false_value。true_value和false_value可以是任何类型。  
The same rules that apply to the CASE expression for Boolean expressions, null handling, and return types also apply to IIF. For more information, see CASE (Transact-SQL).  
适用于布尔表达式,空值处理和返回类型的CASE表达式的相同规则也适用于IIF。有关更多信息,请参见CASE(Transact-SQL)。

The fact that IIF is translated into CASE also has an impact on other aspects of the behavior of this function.  
将IIF转换为CASE的事实也对该功能的行为的其他方面产生影响。  
Since CASE expressions can be nested only up to the level of 10, IIF statements can also be nested only up to the maximum level of 10.   
由于CASE表达式最多只能嵌套10个级别,因此IIF语句也只能最多嵌套10个级别。  
Also, IIF is remoted to other servers as a semantically equivalent CASE expression, with all the behaviors of a remoted CASE expression.  
同样,IIF具有语义等效的CASE表达式,并具有远程CASE表达式的所有行为,从而可以远程访问其他服务器。

参考

微软官方文档 - IIF (Transact-SQL)