iif sql

您所在的位置:网站首页 iif嵌套 iif sql

iif sql

2023-03-09 23:11| 来源: 网络整理| 查看: 265

iif sql

SQL Server 2012 introduced a new built-in logical function SQL IIF. It is a shorthand form of writing CASE statement logic or IF-ELSE logic.

SQL Server 2012引入了新的内置逻辑函数SQL IIF。 它是编写CASE语句逻辑或IF-ELSE逻辑的简写形式。

We explored Case Statement in SQL in my earlier article. We use a case statement to return a result based on the defined condition. It is similar to an IF..ELSE…THEN statement evaluates an expression and returns the output. The case statement is available in almost all versions of SQL Server.

我们在之前的文章中探讨了SQL中的Case语句 。 我们使用case语句根据定义的条件返回结果。 它类似于IF..ELSE…THEN语句计算表达式并返回输出。 case语句在几乎所有版本SQL Server中都可用。

Let’s explore this SQL IIF function in this article.

让我们在本文中探索这个SQL IIF函数。

SQL IIF语句概述 (SQL IIF Statement overview)

We use the following format to write Case statement logic in SQL queries

我们使用以下格式在SQL查询中编写Case语句逻辑

SELECT CASE Expression When expression1 Then Result1 When expression2 Then Result2 … ELSE Result END

SELECT CASE表达式当expression1然后Result1时当expression2然后Result2…ELSE结果结束

We can write this code using SQL IIF statement syntax as following.

我们可以使用SQL IIF语句语法编写此代码,如下所示。

IIF(boolean_expression, true_value, false_value)

IIF(布尔表达式,真值,假值)

Boolean_expression: The first parameter in SQL IIF statement is a boolean expression. It should be a valid boolean expression else we get an exception Boolean_expression :SQL IIF语句中的第一个参数是布尔表达式。 它应该是一个有效的布尔表达式,否则我们会遇到异常 True_Value: If the boolean_expression is TRUE, it returns value specified in the True_Value :如果boolean_expression为TRUE,则返回true_value parameter true_value参数中指定的值 False_Value: If the boolean_expression is FALSE, it returns value specified in the False_Value :如果boolean_expression为FALSE,则它返回在false_value parameter false_value参数中指定的值

Let’s explore SQL IIF statement using examples.

让我们使用示例探索SQL IIF语句。

示例1:用于比较整数值SQL IIF语句 (Example 1: SQL IIF statement for comparing integer values)

In the following example, specified Boolean expression return False ( 2>3 is not TRUE). Due to this, it returns the value specified in the false_value parameter.

在下面的示例中,指定的布尔表达式返回False(2> 3不是TRUE)。 因此,它返回在false_value参数中指定的值。

SELECT IIF(2 > 3, 'TRUE', 'FALSE' )

SQL IIF statement for comparing integer values

Similarly, if the condition is TRUE (5>3 is TRUE) so it returns the value of true_value parameter.

同样,如果条件为TRUE(5> 3为TRUE),则它将返回true_value参数的值。

SELECT IIF(5 > 3, 'TRUE', 'FALSE' )

SQL IIF statement for comparing integer values - FALSE condition 示例2:带有变量SQL IIF语句 (Example 2: SQL IIF statement with variables)

In the following example, we specified two integer variables and assigned values. We use variables for comparison in the IIF statement.

在下面的示例中,我们指定了两个整数变量并分配了值。 我们在IIF语句中使用变量进行比较。

DECLARE @A INT = 80, @B INT = 70 SELECT IIF(@A >= @B, 'PASS', 'FAIL' )

The specified condition (80>70) is TRUE, so it returns the value PASS.

指定的条件(80> 70)为TRUE,因此它返回值PASS。

IIF statement with variable 示例3:比较两个字符串SQL IIF语句 (Example 3: SQL IIF statement to compare two strings)

In the following example, we want to compare the string data using SQL IIF statement. We want to know the person liking based on the person name.

在下面的示例中,我们想使用SQL IIF语句比较字符串数据。 我们想根据个人姓名来了解个人。

DECLARE @Person Varchar(100) = 'Raj' SELECT IIF(@Person='Raj','Likes Apple','NA')

SQL IIF statement to compare two strings

We can specify multiple conditions in SQL IIF statement as well. Let’s define the following condition

我们也可以在SQL IIF语句中指定多个条件。 让我们定义以下条件

Raj and Mohan both likes Apple

Raj和Mohan都喜欢Apple Else all other persons like orange

其他所有其他人都喜欢橙色 DECLARE @Person Varchar(100) = 'Raj' SELECT IIF(@Person in('Raj', 'Mohan'),'Likes Apple','Likes Orange')

Specify multiple conditions

Specify multiple conditions

The query should return Likes Orange if the person name is not in the IN clause. In the following example, person Vinay does not exist in the variable @Person, so it returns value for a false clause.

如果人名不在IN子句中,则查询应返回Likes Orange 。 在下面的示例中,变量@Person中不存在person Vinay ,因此它返回false子句的值。

Specify multiple conditions 示例4:嵌套SQL IIF语句 (Example 4: Nested SQL IIF statement)

We can use Nested SQL IIF statement as well to specify multiple conditions

我们也可以使用Nested SQL IIF语句来指定多个条件

DECLARE @Person VARCHAR(100)= 'Vinay'; SELECT IIF(@Person = 'Raj', 'Likes Apple', IIF(@Person = 'Vinay', 'Likes Orange', 'Person does not exists in the list')) AS Result;

In this SQL IIF function, it checks for the first condition and if the condition is TRUE, it returns the value. In our case, it is FALSE ( Person Vinay does not match with Raj).It checks for the other condition and returns results if it is TRUE.

在此SQL IIF函数中,它将检查第一个条件,如果条件为TRUE,则返回值。 在本例中为FALSE(Person Vinay与Raj不匹配),它检查其他条件并返回结果是否为TRUE。

Nested SQL IIF statement

If none of the conditions is true, it returns the default false message.

如果没有一个条件为真,则返回默认的错误消息。

Nested IIF statement with false condition 示例5:带有表列SQL IIF语句 (Example 5: SQL IIF statement with a table column)

In the previous examples, we either specify values directly in the IIF statement or specified variables for it. Usually, we want to use it with the existing data in a SQL table. We can use the IIF statement with a table column as well.

在前面的示例中,我们直接在IIF语句中指定值或为其指定变量。 通常,我们希望将其与SQL表中的现有数据一起使用。 我们也可以在表列中使用IIF语句。

In the following example, we want to know the supplier name from the PurchaseOrders table in the WideWorldImporters database.

在下面的示例中,我们想从WideWorldImporters数据库的PurchaseOrders表中了解供应商名称。

DECLARE @SupplierID TINYINT= 1; SELECT DISTINCT        @SupplierID AS SupplierID,        IIF(@SupplierID = 1, 'A Datum Corporation', IIF(@SupplierID = 2, 'Contoso, Ltd.',        IIF(@SupplierID = 3, 'Consolidated Messenger',        IIF(@SupplierID = 4, 'Fabrikam, Inc.', 'Humongous Insurance')))) SupplierName FROM [WideWorldImporters].[Purchasing].[PurchaseOrders];  

IIF statement with a table column

If the supplier name does not exist for a particular supplier id, it returns the specified false value in SQL IIF statement.

如果特定供应商ID的供应商名称不存在,它将在SQL IIF语句中返回指定的false值。

IIF statement with a table column 示例6:带有表列和聚合函数SQL IIF语句 (Example 6: SQL IIF statement with a table column and aggregate function) SELECT         SUM(IIF(status = 1, 1, 0)) AS 'Pending',     SUM(IIF(status = 2, 1, 0)) AS 'Processing',     SUM(IIF(status = 3, 1, 0)) AS 'Rejected',     SUM(IIF(status = 5, 1, 0)) AS 'Completed',     COUNT(*) AS Total FROM         [AdventureWorks2017].[Sales].[SalesOrderHeader] WHERE     YEAR(shipdate) = 2014;

Use of aggregated function with IIF 示例7:SQL IIF语句和数据类型优先级 (Example 7: SQL IIF statement and data type precedence)

We might have different data types for the results. If we have different data types specified in the result conditions, SQL Server gives the highest precedence data type. In the following example, for the false condition(11>19), the result will be the false_value argument, i.e. 100. It should be of e integer data type, but we get the output 40.0 because the other argument float (2.6) is of high precedence than an integer.

我们的结果可能有不同的数据类型。 如果在结果条件中指定了不同的数据类型,则SQL Server会提供最高优先级的数据类型。 在下面的示例中,对于false条件(11> 19),结果将为false_value参数,即100。它应为e整数数据类型,但由于另一个参数float(2.6)为,因此我们得到的输出为40.0。优先级高于整数。

SELECT IIF(11 > 19, 2.6, 40)

data type precedence

You can check the data type precedence in the following image

您可以在下图中检查数据类型的优先级

data type precedence 示例8:带有NULL值SQL IIF (Example 8: SQL IIF with NULL values)

We should be careful in NULL values inside the SQL IIF function.

我们应该注意SQL IIF函数中的NULL值。

SELECT       IIF(100 > 99, NULL, NULL) AS Result;  

We cannot specify NULL in both the true and false arguments. We get the following error message.

我们不能在true和false参数中都指定NULL。 我们收到以下错误消息。

Msg 8133, Level 16, State 1, Line 1 At least one of the result expressions in a CASE specification must be an expression other than the NULL constant.

消息8133,级别16,状态1,行1 CASE规范中的至少一个结果表达式必须是NULL常量以外的表达式。

In the error message, you can see it gives information about the CASE specification however we used SQL IIF function. We will look at this in the next example.

在错误消息中,您可以看到它提供了有关CASE规范的信息,但是我们使用了SQL IIF函数。 我们将在下一个示例中对此进行研究。

You should specify at least one of a true or false argument.

您应至少指定一个true或false参数。

SELECT       IIF(100 > 99, 'Hello', NULL) AS Result;

NULL values in IIF SQL IIF语句和CASE语句之间的相似性 (The similarity between SQL IIF statement and CASE Statement )

In the introduction of SQL IIF Statement, we mentioned that it is a shorthand form of writing CASE statement logic or IF-ELSE logic. Yes, it is true. Internally SQL Server converts the statement into the CASE statement and executes. We can check it using the actual execution plan of a query.

在SQL IIF语句的介绍中,我们提到了它是编写CASE语句逻辑或IF-ELSE逻辑的简写形式。 是的,它是真的。 SQL Server在内部将语句转换为CASE语句并执行。 我们可以使用查询的实际执行计划来检查它。

Execute the query from Example 6 with an Actual execution plan.

使用实际执行计划执行示例6中的查询。

Actual execution plan

In the actual execution plan, look at the properties of Compute Scalar. You can see it executes the CASE statement internally.

在实际的执行计划中,查看Compute Scalar的属性。 您可以看到它在内部执行CASE语句。

CASE statement and IIF

结论 (Conclusion)

In this article, we explored the SQL IIF Statement that is a new way of writing CASE statement related conditions. It is available from SQL 2012 onwards. You should explore this to be familiar with this. If you have any comments or questions, feel free to leave them in the comments below.

在本文中,我们探讨了SQL IIF语句,这是一种编写CASE语句相关条件的新方法。 从SQL 2012起可用。 您应该对此进行探索以熟悉它。 如果您有任何意见或疑问,请随时将其留在下面的评论中。

翻译自: https://www.sqlshack.com/overview-of-sql-iif-statement/

iif sql



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3