This article explores the string manipulation using SQL Coalesce function in SQL Server.

本文探讨了在SQL Server中使用SQL Coalesce函数进行的字符串操作。

String manipulation is a process to generate another form of existing data in a way the business uses or displayed as results in the reports. Previous SQL string function articles, I have written, including SQL string functions for Data Munging and SQL Substring function overview discussed data preparation and data management tasks using built-in SQL Server string functions.

字符串操作是一种以业务使用或在报告中显示为结果的方式生成另一种形式的现有数据的过程。 我以前写过有关SQL字符串函数的文章,其中包括用于Data Munging的 SQL字符串函数和SQL Substring函数概述,讨论了使用内置SQL Server字符串函数进行的数据准备和数据管理任务。

SQL server also has some built-in character functions that also allow us to manipulate and transform data. At the same time, it is important to examine dataset, explore data values and encode or decode the values, as necessary, to generate meaningful data. It is important to know how to navigate through missing values in our datasets, understanding impact on calculations, queries, reports and data-set preparation and coming up with techniques to avoid letting Null values ruin our resultsets.

SQL Server还具有一些内置的字符功能,这些功能也使我们能够处理和转换数据。 同时,重要的是检查数据集,探索数据值并根据需要对值进行编码或解码,以生成有意义的数据。 重要的是要知道如何导航数据集中的缺失值,了解对计算,查询,报告和数据集准备的影响,并提出避免空值破坏我们的结果集的技术。

什么是NULL值? (What is a NULL value?)

Before we delve into how to navigate the potential minefield of datasets with missing values and avoid stepping on a Null, let’s first take a quick look at what a NULL is.

在深入研究如何导航缺少值的数据集的潜在雷区并避免踩到Null之前,让我们先快速了解一下NULL是什么。

As defined by Wikipedia

根据维基百科的定义

Null (or NULL) is a special marker used in Structured Query Language to indicate that a data value does not exist in the database. Introduced by the creator of the relational database model, E. F. Codd, SQL Null serves to fulfil the requirement that all true relational database management systems (RDBMS) support a representation of “missing information and inapplicable information”. Codd also introduced the use of the lowercase Greek omega (ω) symbol to represent Null in database theory. In SQL, NULL is a reserved word used to identify this marker. … This should not be confused with a value of 0. A null value indicates a lack of a value — a lack of a value is not the same thing as a value of zero in the same way that a lack of an answer is not the same thing as an answer of “no”.

空(或NULL)是在结构化查询语言中使用的特殊标记,用于指示数据库中不存在数据值。 由关系数据库模型的创建者EF Codd引入SQL Null可以满足所有真正的关系数据库管理系统(RDBMS)支持“缺少信息和不适用信息”表示的要求。 Codd还介绍了使用小写的希腊omega(ω)符号来表示数据库理论中的Null。 在SQL中,NULL是用于标识此标记的保留字。 …不应将其与0值混淆。null值表示缺少值-缺少值与0值不一样,这与缺少答案不是与否定答案相同。

Furthermore …

此外...

SQL null is a state, not a value. This usage is quite different from most programming languages, where null value of a reference means it is not pointing to any object.

SQL null是状态,而不是值。 这种用法与大多数编程语言完全不同,在大多数编程语言中, 引用的 null值 表示未指向任何对象。

SQL does provide some handy functionality for working with your character data in your SQL queries that we’ll describe in detail

SQL确实提供了一些方便的功能来处理您SQL查询中的字符数据,我们将对此进行详细介绍

SQL Coalesce函数 (SQL Coalesce function)

The SQL Coalesce and IsNull functions are used to handle NULL values. During the expression evaluation process the NULL values are replaced with the user-defined value.

SQL Coalesce和IsNull函数用于处理NULL值。 在表达式求值过程中,NULL值将替换为用户定义的值。

The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.

SQL Coalesce函数按顺序评估参数,并始终从定义的参数列表中返回第一个非空值。

Syntax

句法

COALESCE ( expression [ 1…n ] )

COALESCE(表达式[1…n])

SQL Coalesce函数的属性 (Properties of the SQL Coalesce function)

  1. Expressions must be of same data-type 表达式必须具有相同的数据类型
  2. It can contain multiple expressions 它可以包含多个表达式
  3. The SQL Coalesce function is a syntactic shortcut for the Case expression SQL Coalesce函数是Case表达式的语法快捷方式
  4. Always evaluates for an integer first, an integer followed by character expression yields integer as an output. 始终先求整数,然后跟字符表达式的整数会得出整数作为输出。

例子: (Examples:)

SELECT COALESCE (NULL,'A','B')
SELECT COALESCE (NULL,100,20,30,40)
SELECT COALESCE (NULL,NULL,20,NULL,NULL)
SELECT COALESCE (NULL,NULL,NULL,NULL,NULL,'Prashanth')
SELECT COALESCE (NULL,NULL,NULL,NULL,1,'Prashanth')
SELECT COALESCE (NULL,NULL,NULL,NULL,NULL,'Prashanth',1)

字符串连接操作中SQL Coalesce (SQL Coalesce in a string concatenation operation)

In the following example, we’re going to concatenate some values. But, again, it’s just a review to let you know what happens when we have a NULL value. So, let’s go ahead and execute the T-SQL. And we can see that we encounter a NULL value while processing string concatenation operation. SQL server simply returns NULL whenever it encounters NULL value. The result is not a combination of the firstname, null, and last name.

在下面的示例中,我们将连接一些值。 但是,再次提醒您,当我们使用NULL值时会发生什么。 因此,让我们继续执行T-SQL。 我们可以看到在处理字符串连接操作时遇到了NULL值。 SQL Server在遇到NULL值时仅返回NULL。 结果不是名字,空值和姓氏的组合。

SELECT firstName +' '+MiddleName+' '+ LastName FullName FROM Person.Person

Let us handle the NULL values using a function called SQL COALESCE. It allows handling the behavior of the NULL value. So, in this case, use the coalesce SQL function to replace any middle name NULL values with a value ‘ ‘ (Char(13)-space). The SQL statement should still concatenate all three names, but no NULL values will show up in the output. We now see that the full name gets displayed with a space in the middle, for NULL values. In this way, it is possible to efficiently customize the column values.

让我们使用一个称为SQL COALESCE的函数处理NULL值。 它允许处理NULL值的行为。 因此,在这种情况下,请使用合并SQL函数将所有中间名NULL值替换为值''(Char(13)-space)。 SQL语句仍应连接所有三个名称,但是输出中不会显示NULL值。 现在,我们看到全名在中间显示一个空格,表示NULL值。 这样,可以有效地自定义列值。

SELECT firstName +' '+COALESCE(MiddleName,'') +' '+ LastName  FROM Person.Person

SQL Coalesce函数和透视 (SQL Coalesce function and pivoting)

The following example returns the concatenated non-null values from the table ‘state’. In some cases, you may need to assign the concatenated static values to a variable. In this case, the values of the city column are parsed using the Coalesce SQL function and concatenated within a single quote to prepare a string of values. The output is then further manipulated to remove the last character to fetch a valid string of input value.

以下示例从表“ state”返回串联的非null值。 在某些情况下,您可能需要将串联的静态值分配给变量。 在这种情况下,使用Coalesce SQL函数解析city列的值,并将其串联在单引号内以准备值字符串。 然后,对输出进行进一步处理,以删除最后一个字符,以获取有效的输入值字符串。

DROP TABLE IF EXISTS STATE;
CREATE TABLE STATE
(
CITY VARCHAR(50),
STATE VARCHAR(500))INSERT INTO STATE VALUES('Appleton','WI'),('Milwaukee','WI'),('Madison','WI'),('Miami','Florida'),('Jacksonville','Florida')DECLARE @col nvarchar(MAX);
SELECT @col = COALESCE(@col,'') +''''+CITY +''''+ ','
FROM dbo.STATE WHERE state = 'WI';SELECT substring(@col,1,len(@col)-1)

Output:

输出:

SELECT '('+substring(@col,1,len(@col)-1)+')'

标量用户定义函数和SQL Coalesce函数 (Scalar user-defined function and SQL Coalesce function)

A user-defined function is created to return a string specific to the provided input and then the output is grouped using a grouping clause. In the following example, the scalar valued function returns the concatenated string values separated by ‘,’ for a specified ‘City’ input. The following example returns an output where the state column is grouped and its cities values are concatenated and separated by a delimiter ‘,’ (comma). You can also user STRING_AGG if you’re using SQL Server 2017. You can refer more information with the article Top SQL string functions in SQL Server 2017

创建用户定义的函数以返回特定于所提供输入的字符串,然后使用分组子句对输出进行分组。 在下面的示例中,标量值函数为指定的“城市”输入返回以“,”分隔的串联字符串值。 下面的示例返回一个输出,其中“ 状态”列被分组,并且其城市值由定界符“,”(逗号)连接和分隔。 如果您使用的是SQL Server 2017,也可以使用STRING_AGG 。有关更多信息,请参阅文章SQL Server 2017中的顶级SQL字符串函数。


CREATE FUNCTION dbo.tfn_CoalesceConcat
(@state varchar(100)
)
RETURNS NVARCHAR(MAX)
AS
BEGINDECLARE @str NVARCHAR(MAX);SELECT @str = COALESCE(@str + ', ', '') + CITYFROM dbo.STATEWHERE state = @stateORDER BY state;RETURN (@str);
END
GO

Here is how we call the function name dbo.tfn_CoalesceConcat in the select statement.

这就是我们在select语句中调用函数名称dbo.tfn_CoalesceConcat的方式。

The output is a concatenated stream of values separated by a delimiter ‘,’

输出是由分隔符','分隔的串联值流

SELECT state, city = dbo.tfn_CoalesceConcat(state)FROM dbo.stateGROUP BY stateORDER BY state;

使用SQL Coalesce函数进行数据验证 (Data validation using SQL Coalesce function)

In the following example, we are going to find the emergency employee contacts. Usually, in any organization, the employee’s phone numbers are listed under work, home, cell phone columns.

在以下示例中,我们将查找紧急员工联系人。 通常,在任何组织中,员工的电话号码都列在工作,家庭,手机列下。

Let us see how to find employees where no emergency contacts are listed or, in other words, let’s pull all the details of the employee with emergency contacts.

让我们看看如何找到未列出紧急联系人的员工,或者换句话说,让我们提取具有紧急联系人的员工的所有详细信息。

In the following example, the tb_EmergencyContact holds the contact numbers of all employees.

在以下示例中,tb_EmergencyContact保留所有员工的联系电话。

DROP TABLE IF EXISTS tb_EmergencyContact;CREATE  TABLE tb_EmergencyContact  (empid int,firstname   VARCHAR(100) NOT NULL,lastname    VARCHAR(100) NOT NULL,relationship VARCHAR(100),homephone   VARCHAR(25),workphone   VARCHAR(25),cellphone   VARCHAR(25)); INSERT INTO tb_EmergencyContact ( empid, firstname, lastname, relationship, homephone, workphone, cellphone )
VALUES ( 1,'Ambika','Prashanth','Wife',NULL,'920.176.1456','928.132.2967' ),( 2,'Prashanth','Jayaram','spouse',NULL,NULL,'982.132.2867' ),( 3,'Pravitha','Prashanth','Daughter',NULL,NULL,NULL )

The SQL Coalesce function is used to select the columns homephone, workphone, and cellphone. In case of NULL values, the value ‘NA’ (not applicable), a literal string is returned.

SQL Coalesce函数用于选择“家庭电话”,“工作电话”和“手机”列。 如果为NULL值,则返回值'NA'(不适用),并返回文字字符串。

SELECTfirstname+''+lastname fullname,relationship,COALESCE(homephone, workphone, cellphone, 'NA') phone
FROMdbo.tb_EmergencyContact

SQL合并和计算列 (SQL Coalesce and Computed columns)

The following example uses SQL COALESCE to compare the values of the hourlywage, salary, and commission columns and return only the non-null value found in the columns.

下面的示例使用SQL COALESCE来比较小时工资,薪水和佣金列的值,并仅返回在列中找到的非空值。

CREATE TABLE EMP
(EMPNO INT NOT NULL,
ENAME VARCHAR(20),
JOB VARCHAR(10),
MGR INT,
JOINDATE DATETIME,
HOURLYWAGE DECIMAL(7,2),
SALARY DECIMAL(7, 2),
COMMISSION DECIMAL(7, 2),
NUMSALES DECIMAL(7,2),
DNO INT)INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, '02-MAR-1970',NULL, 8000, NULL, 20,2),
(7499, 'ALLEN', 'SALESMAN', 7698, '20-MAR-1971',NULL, 1600, 3000,4, 3),
(7521, 'WARD', 'SALESMAN', 7698, '07-FEB-1983', 40,1250, 5000,10, 3);

The following T-SQL is used to list the total salary paid to all the employees

以下T-SQL用于列出支付给所有员工的总薪水

SELECT EMPNO,ENAME,CAST(COALESCE(HOURLYWAGE * 40 * 52,   salary,   Salary+(COMMISSION * NUMSALES)) AS decimal(10,2)) AS TotalSalary
FROM dbo.EMP
ORDER BY TotalSalary;

Now, Let us see an example to create a computed column with SQL Coalesce function in SQL Server

现在,让我们来看一个在SQL Server中使用SQL Coalesce函数创建计算列的示例

In general, we may need to use the expression in the tables. In tables, it is required to compute the values that are often calculated using several existing columns and with few scalar values of the table. Also, these columns are dependent on one or more other columns. In this way, we can create a computed column using the Coalesce SQL function so that NULL values are efficiently handled.

通常,我们可能需要在表中使用表达式。 在表中,需要计算通常使用几个现有列且表的标量值很少的值。 同样,这些列依赖于一个或多个其他列。 这样,我们可以使用Coalesce SQL函数创建一个计算列,以便有效地处理NULL值。

ALTER TABLE dbo.EMP
ADD Total_Salary ASCAST(COALESCE(HOURLYWAGE * 40 * 52,   salary,   Salary+(COMMISSION * NUMSALES)) AS decimal(10,2))select * from EMP

Now, you can see that a simple SELECT statement displays the pre-calculated results.

现在,您可以看到一个简单的SELECT语句显示了预先计算的结果。

SQL COALESCE和CASE表达式 (SQL COALESCE and CASE expression)

The SQL COALESCE function can be syntactically represented using the CASE expression. For example, as we know, the Coalesce function returns the first non-NULL values.

可以使用CASE表达式在语法上表示SQL COALESCE函数。 例如,众所周知,Coalcece函数返回第一个非NULL值。

SELECT COALESCE (expression1, expression2, expression3) FROM TABLENAME;

从TABLENAME中选择COALESCE(表达式1,表达式2,表达式3);

The above Coalesce SQL statement can be rewritten using the CASE statement.

可以使用CASE语句重写上面的Coalesce SQL语句。

SELECTfirstname+''+lastname fullname,relationship,CASE WHEN homephone is NOT NULL Then homephoneWHEN cellphone is NOT NULL Then cellphoneWHEN workphone is NOT NULL Then workphoneELSE 'NA'ENDEmergencyContactNumber
FROMdbo.tb_EmergencyContact

The query returns the same result as the one that uses the COALESCE function.

该查询返回的结果与使用COALESCE函数的结果相同。

结语 (Wrap Up)

In this article, we discussed some tip and tricks to demonstrate the use of the SQL Coalesce function to query effectively with the T-SQL. We also discussed various use-cases of the SQL Coalesce function. It is also possible to optimize output by creating a computed column.

在本文中,我们讨论了一些技巧和窍门,以演示如何使用SQL Coalesce函数通过T-SQL有效地进行查询。 我们还讨论了SQL Coalesce函数的各种用例。 也可以通过创建计算列来优化输出。

I hope you enjoyed this article on the Coalesce function in SQL Server. Feel free ask any questions in the comments below.

希望您喜欢有关SQL Server中的Coalesce函数的文章。 请随时在下面的评论中提问。

翻译自: https://www.sqlshack.com/using-the-sql-coalesce-function-in-sql-server/

在SQL Server中使用SQL Coalesce函数相关推荐

  1. SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题

    SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题 原文:SQL SERVER中用户定义标量函数(scalar user defined fu ...

  2. SQL SERVER中LEAD和LAG函数

    SQL SERVER中LEAD和LAG函数 LEAD和LAG函数 LEAD 访问相同结果集的后续行中的数据,而不使用 SQL Server 2012 中的自联接. LEAD 以当前行之后的给定物理偏移 ...

  3. 【转】在SQL Server中通过SQL语句实现分页查询

    在SQL Server中通过SQL语句实现分页查询 2008年01月06日 星期日 12:28 建立表: CREATE TABLE [TestTable] ( [ID] [int] IDENTITY ...

  4. SQL Server中截取字符串常用函数

    SQL Server 中截取字符串常用的函数: 1.LEFT ( character_expression , integer_expression ) 函数说明:LEFT ( '源字符串' , '要 ...

  5. SQL Server中时间格式转换函数convert()的使用

    convert(varchar(10),字段名,转换格式) CONVERT为日期转换函数,一般就是在时间类型(datetime,smalldatetime)与字符串类型(nchar,nvarchar, ...

  6. SQL Server中的SQL语句优化与效率问题

    很多人不知道SQL语句在SQL SERVER中是如何执行的,他们担心自己所写的SQL语句会被SQL SERVER误解.比如: select * from table1 where name='zhan ...

  7. 如何在SQL Server中创建SQL依赖关系图

    Deleting or changing objects may affect other database objects like views or procedures that depends ...

  8. 转储sql文件_在Linux上SQL Server中更改SQL转储文件位置

    转储sql文件 In this article, we will talk about SQL Dump files and the process to change the dump direct ...

  9. SQL server中使用SQL语句创建表基础步骤

    基本代码 创建 StudentInfo 表: create table StudentInfo (-- 设置主键,并添加标识sID int not null primary key identity( ...

最新文章

  1. JavaScript实现trial Division试除法算法(附完整源码)
  2. php实现多进程、多线程
  3. Cache超清晰逻辑详解----不一致性(待更)
  4. golang 的交叉编译
  5. bpmn流程图_流程图怎么做?金舟在线流程图教你高逼格制作
  6. LOJ3119 CTS2019 随机立方体 概率、容斥、二项式反演
  7. c++ 使用正则匹配url
  8. c++_string与double/int互转
  9. mysql数据库丢失还原_MySQL数据库丢失后如何自动恢复呢?
  10. Objective-C和C++语法比较
  11. c语言令牌桶原理,令牌桶算法及实现(二)
  12. 云计算给IT产业结构带来的影响 .
  13. 建设工程项目全寿命周期管理是指_建设工程全寿命周期的概述
  14. unicast、multicast和broadcast
  15. 信息安全软考——关于DES初始置换表解答题
  16. 基于企业微信机器人实现预警功能
  17. AnySim一键解锁教程nbsp;只适用于新iPhone
  18. MySQL数据库学习(二)
  19. 华师计算机学院2014级,华师,新生早知道
  20. 04.千淘万漉虽辛苦,吹尽黄沙始到金——SQL Server大数据群集初探

热门文章

  1. 如何在cocoapods中使用更新版本的pod
  2. 【洛谷新手村】简单字符串 p1055 ISBN号码
  3. codevs 5958 无
  4. java 开发微信中回调验证一直提示 解密失败处理(Java)
  5. opencv新手注意
  6. 开始学习python标准库---os
  7. (进阶)LeetCode(766)——托普利茨矩阵(JavaScript)
  8. npm ERR! code ENOENT npm ERR! syscall open npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file
  9. JavaScript学习 第二课(二)
  10. oracle如何查看实例用户,oracle 如何显示当前执行的用户和操作实例