sql concat函数

This article explores SQL Server Concatenate operations using the SQL Plus (+) operator and SQL CONCAT function.

本文探讨了使用SQL Plus(+)运算符和SQL CONCAT函数SQL Server串联操作。

介绍 (Introduction)

We use various data types in SQL Server to define data in a particular column appropriately. We might have requirements to concatenate data from multiple columns into a string. For example, in an Employee table, we might have first, middle and last name of an employee in different columns.

我们在SQL Server中使用各种数据类型来适当地定义特定列中的数据。 我们可能需要将多个列中的数据连接成一个字符串。 例如,在Employee表中,我们可能在不同的列中具有雇员的名字,中间名和姓氏。

In the following screenshot, we have top 10 records from an employee table whose middle name is NOT NULL (I will explain the reason for it as we move on in this article)

在下面的屏幕截图中,我们有一个雇员表的前10条记录,其中间名不是NOT NULL(在本文中,我将解释其原因)

SELECT TOP (10) [FirstName], [MiddleName], [LastName]
FROM [AdventureWorks2017].[Person].[Person]
where Middlename IS NOT NULL

SQL Plus操作员概述 (SQL Plus Operator Overview)

Usually, we use a SQL Plus (+) operator to perform SQL Server Concatenate operation with multiple fields together. We can specify space character as well in between these columns.

通常,我们使用SQL Plus(+)运算符对多个字段一起执行SQL Server串联操作。 我们也可以在这些列之间指定空格字符。

SQL Plus(+)运算符的语法 (Syntax of SQL Plus(+) operator)

string1 + string2 + …….stringn

字符串1 +字符串2 + .......字符串

SQL Plus(+)运算符的示例 (Examples of SQL Plus(+) Operator)

Look at the following query. In this query, we use SQL Plus(+) operator and space between the single quote as a separator between these fields.

查看以下查询。 在此查询中,我们使用SQL Plus(+)运算符和单引号之间的空格作为这些字段之间的分隔符。

SELECT TOP 10 FirstName, MiddleName, LastName, FirstName + ' ' + MiddleName + ' ' + LastName AS FullName
FROM [AdventureWorks2017].[Person].[Person]
WHERE Middlename IS NOT NULL;

In the output of SQL Server Concatenate using SQL Plus (+) operator, we have concatenate data from these fields (firstname, MiddleName and LastName) as a new column FullName.

在使用SQL Plus(+)运算符SQL Server连接的输出中,我们将这些字段(名字,中间名和姓)中的数据连接为新列FullName。

We have a drawback in SQL Server Concatenate data with SQL Plus(+) operator. Look at the following example.

SQL Server使用SQL Plus(+)运算符连接数据时,我们有一个缺点。 看下面的例子。

SELECT TOP 10 FirstName, MiddleName, LastName, FirstName + ' ' + MiddleName + ' ' + LastName AS FullName
FROM [AdventureWorks2017].[Person].[Person]

In this example, we can see that if we have any NULL value present in any fields, we get output of concatenate string as NULL with SQL Plus(+) operator.

在此示例中,我们可以看到,如果任何字段中都存在NULL值,则使用SQL Plus(+)运算符将连接字符串的输出输出为NULL

We can use SQL ISNULL function with + operator to replace NULL values with a space or any specific value. Execute the following query and we can still use SQL Plus(+) operator to concatenate string for us.

我们可以使用带有+运算符的SQL ISNULL函数,将NULL值替换为空格或任何特定值。 执行以下查询,我们仍然可以使用SQL Plus(+)运算符为我们连接字符串。

SELECT TOP 10 FirstName, MiddleName, LastName, ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') + ' ' + ISNULL(LastName, '') AS FullName
FROM [AdventureWorks2017].[Person].[Person];

Let’s look at another example of SQL Server Concatenate values with string as well as numeric values. In the following query, we want to concatenate first, middle, full name along with the NationalID number.

让我们看一下SQL Server连接字符串和数字值的另一个示例。 在以下查询中,我们希望将名字,中间名,全名以及NationalID号连接起来。

SELECT p.[Title], p.[FirstName], p.[MiddleName], p.[LastName], p.FirstName + ' ' + p.MiddleName + ' ' + p.LastName + 'NationalIDNumber is :' + e.NationalIDNumber AS EmpDetail
FROM [HumanResources].[Employee] eINNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = e.[BusinessEntityID]
WHERE p.Middlename IS NOT NULL;

Suppose we want the single quote as well in the SQL Server Concatenate. In SQL Server, once we combine strings using SQL Plus(+) operator, it concatenates values inside single quotes. In the following query, we can see we specified two single quotes to display a single quote in the output.

假设我们也希望在SQL Server连接中使用单引号。 在SQL Server中,一旦我们使用SQL Plus(+)运算符组合了字符串,它将在单引号内连接值。 在下面的查询中,我们可以看到我们指定了两个单引号以在输出中显示一个单引号。

SELECT 'Let''s' + ' explore SQL Server with articles on SQLShack';

If there is any mismatch or incorrect use of the single quote, you get following error message.

如果单引号不匹配或使用不正确,则会出现以下错误消息。

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ‘ + ‘.
Msg 319, Level 15, State 1, Line 4
Incorrect syntax near the keyword ‘with’. If this statement is a common table expression,
an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Msg 105, Level 15, State 1, Line 4
Unclosed quotation mark after the character string ‘;
‘.

Msg 102,第15级,状态1,第4行
'+'附近的语法不正确。
消息319,第15级,州1,第4行
关键字“ with”附近的语法不正确。 如果该语句是公用表表达式,
xmlnamespaces子句或变更跟踪上下文子句,则前一条语句必须以分号终止。
Msg 105,第15级,第1行,第4行
字符串';后的右引号
'。

If we want to print more single quotes, we need to define in the string in the following format with two single quotes.

如果要打印更多的单引号,则需要在字符串中以以下格式定义两个单引号。

Expected Output: ‘Let’s explore SQL Server with articles on SQLShack’

预期输出 :“让我们通过SQLShack上的文章探索SQL Server”

We can modify SQL query as follow.

我们可以如下修改SQL查询。

SELECT '''Let''s' + ' explore SQL Server with articles on SQLShack''';
  • Note: You should not confuse a single quote with the double quotes. SQL Server treats double quotes as a character.
  • 注意 :请勿将单引号与双引号混淆。 SQL Server将双引号视为一个字符。

In the following query, we used a double quote in a combination of a single quote.

在以下查询中,我们将双引号与单引号组合使用。

SELECT '"''Let''s' + ' explore SQL Server with articles on SQLShack''';

We can do SQL Server Concatenate operation using the SQL Plus(+) operator; however, it becomes complex if you need to use multiple single quotes. It is difficult to debug code as well since you need to look at all the single quotes combinations as well.

我们可以使用SQL Plus(+)运算符执行SQL Server串联操作; 但是,如果需要使用多个单引号,它将变得很复杂。 同样,调试代码也很困难,因为您还需要查看所有单引号组合。

SQL CONCAT功能 (SQL CONCAT FUNCTION)

Starting from SQL Server 2012, we have a new function to concatenate strings in SQL Server.

从SQL Server 2012开始,我们有了一个新功能来连接SQL Server中的字符串。

SQL CONCAT函数的语法 (Syntax of SQL CONCAT function)

CONCAT ( string1, string2….stringN)

CONCAT(string1,string2….stringN)

We require at least two values to concatenate together and specify in the SQL CONCAT function.

我们需要至少两个值连接在一起并在SQL CONCAT函数中指定。

例子 (Examples)

Let’s explore SQL CONCAT with an example. The following query, concatenate string and gives output as a single string. We specified multiple single quotes between each word to print space in between each word.

让我们用一个例子来探讨SQL CONCAT。 以下查询将字符串连接起来,并将输出作为单个字符串给出。 我们在每个单词之间指定了多个单引号,以在每个单词之间打印空格。

SELECT CONCAT( 'My',' ', 'Name',' ', 'is',' ', 'Rajendra',' ', 'Gupta') AS introduction

We can use system functions as well in concatenate sting using SQL CONCAT function.

我们也可以在使用SQL CONCAT函数的串联字符串中使用系统函数。

SELECT CONCAT( 'SQL ISNULL function published on',' ',GETDATE()-2) AS SingleString

We use Getdate() function to get a specified date in a concatenated string as well.

我们也使用Getdate()函数来获取连接字符串中的指定日期。

In the previous section, we explored that if we want to concatenate string using + operator and any of string has a NULL value, and we get the output as NULL. We use SQL ISNULL function to replace NULL values in the string. We need to use SQL ISNULL with each column containing NULL values. If we have a large number of the column that may have NULL values, it becomes complex to write such code.

在上一节中,我们探讨了如果要使用+运算符来连接字符串,并且任何一个字符串都具有NULL值,则输出将为NULL。 我们使用SQL ISNULL函数替换字符串中的NULL值。 我们需要对每个包含NULL值的列使用SQL ISNULL。 如果我们有大量可能具有NULL值的列,那么编写这样的代码将变得很复杂。

Let’s review this again with SQL CONCAT function. We only need to specify the SQL CONCAT function at once and specify all string columns. We get the output as a concatenated string.

让我们再次使用SQL CONCAT函数对此进行回顾。 我们只需要立即指定SQL CONCAT函数并指定所有字符串列。 我们将输出作为连接字符串。

SELECT TOP 10 FirstName, MiddleName, LastName, CONCAT(FirstName, ' ',MiddleName,' ',LastName) AS FullName
FROM [AdventureWorks2017].[Person].[Person];
  • Note: If all the string passed in SQL CONCAT function have a NULL value, we get the output of this function also NULL.注意:如果在SQL CONCAT函数中传递的所有字符串都具有NULL值,则我们将获得此函数的输出也为NULL。

SQL CONCAT和数据类型转换 (SQL CONCAT and data type conversion)

SQL CONCAT function implicitly converts arguments to string types before concatenation. We can use SQL CONVERT function as well without converting the appropriate data type.

SQL CONCAT函数在连接之前将参数隐式转换为字符串类型。 我们也可以使用SQL CONVERT函数,而无需转换适当的数据类型。

If we concatenate string using the plus( +) operator, we need to use SQL CONVERT function to convert data types. Lets’ look this using the following example.

如果使用plus(+)运算符连接字符串,则需要使用SQL CONVERT函数转换数据类型。 让我们用下面的例子来看一下。

In the following query, we want to concatenate two strings. In this example, data type of first string is Text while another data type is a date.

在下面的查询中,我们要连接两个字符串。 在此示例中,第一个字符串的数据类型是Text,而另一个数据类型是日期。

Declare @Text Varchar(100)='Microsoft SQL Server 2019 Community Technology Preview 2.5 launched on'
Declare @date date='20190422'
Select @Text +' '+ @date as Result

Execute this query, and we get the following output.

执行此查询,我们得到以下输出。

Msg 402, Level 16, State 1, Line 3
The data types varchar and date are incompatible in the add operator.

消息402,级别16,状态1,第3行
数据类型varchar和date在add运算符中不兼容。

We need to use SQL CONVERT function as per the following query, and it returns output without error message.

我们需要根据以下查询使用SQL CONVERT函数,它返回的输出无错误消息。

Declare @Text Varchar(100)='Microsoft SQL Server 2019 Community Technology Preview 2.5 launched on'
Declare @date date='20190422'
Select @Text+' '+Convert (varchar,(@date)) as Result

We do not need to use SQL CONVERT function to convert data type in SQL CONCAT function. It automatically does the conversion based on the input data type.

我们不需要使用SQL CONVERT函数来转换SQL CONCAT函数中的数据类型。 它根据输入数据类型自动进行转换。

Declare @Text Varchar(100)='Microsoft SQL Server 2019 Community Technology Preview 2.5 launched on'
Declare @date date='20190422'
Select concat(@Text,@date) as Result

In the following table, we can see that data type conversion for input and output data types in SQL CONCAT function.

在下表中,我们可以看到SQL CONCAT函数中针对输入和输出数据类型的数据类型转换。

Input Data Type

Output Data Type

SQL CLR

NVARCHAR(MAX)

NVARCHAR(MAX)

NVARCHAR(MAX)

NVARCHAR(<=4000 characters)

NVARCHAR(<=4000 characters)

VARBINARY(MAX)

NVARCHAR(MAX)

All other data types

VARCHAR(<=8000) *if any parameters data type is NVARCHAR, the output value will be NVARCHAR(MAX)

输入数据类型

输出数据类型

SQL CLR

NVARCHAR(最大)

NVARCHAR(最大)

NVARCHAR(最大)

NVARCHAR(<= 4000个字符)

NVARCHAR(<= 4000个字符)

VARBINARY(最大)

NVARCHAR(最大)

所有其他数据类型

VARCHAR(<= 8000)*如果任何参数数据类型为NVARCHAR,则输出值为NVARCHAR(MAX)

结论 (Conclusion)

In this article, we explored useful SQL functions to concatenate multiple values together using the SQL Plus(+) operator and SQL CONCAT function. If you had comments or questions, feel free to leave them in the comments below.

在本文中,我们探索了有用SQL函数,以使用SQL Plus(+)运算符和SQL CONCAT函数将多个值连接在一起。 如果您有任何意见或问题,请随时将其留在下面的评论中。

翻译自: https://www.sqlshack.com/sql-server-concatenate-operations-with-sql-plus-and-sql-concat-functions/

sql concat函数

sql concat函数_使用SQL Plus(+)和SQL CONCAT函数SQL Server CONCATENATE操作相关推荐

  1. sql md5函数_【学习笔记】常见漏洞:SQL注入的利用与防御

    第   21 课   SQL注入的利用与防御 课程入口(付费) 个人背景 李,本科,电子信息工程专业,毕业一年半,有JavaScript的,PHP,Python的语言基础,目前自学网络安全中. SQL ...

  2. concat函数_三、P57-61 MySQL中常用函数

    本部分主要讲解MySQL数据库中常用函数的使用. P57 SQL中的函数类型:字符串函数.数值函数.日期和时间函数.流程函数.其他常用函数: P58 第1部分:字符串函数 1.concat函数 con ...

  3. python怎么和sql一起用_自己写的Python数据库连接类和sql语句拼接方法

    这个工具类十分简单和简洁. sql拼接方法 # encoding=utf-8 from django.http import HttpResponse from anyjson import seri ...

  4. idea打印sql的插件_[Mybatis]-[基础支持层]-插件-自定义简易SQL打印插件

    该系列文章针对 Mybatis 3.5.1 版本 在 mybatis 中允许针对 SQL 在执行前后进行扩展操作,而这些扩展操作也叫做插件. 在 Mybaits 中允许用插件来拦截的方法包括: Exe ...

  5. mysql数据库div函数_关于使用mysql中的div函数报错?报错-问答-阿里云开发者社区-阿里云...

    数据库MySQL 5.5.27 jar包:mysql-connector-java-5.1.21.jar mybatis-spring-1.1.1.jar druid-0.2.10.jar 集成myb ...

  6. python生成器函数_【python】生成器和生成器函数

    1.生成器函数: 普通函数: def func(): print("周杰伦") return "昆凌" func() #执行func()函数,"周杰伦 ...

  7. 原生js已载入就执行函数_手写CommonJS 中的 require函数

    前言 来自于圣松大佬的文章<手写CommonJS 中的 require函数> 什么是 CommonJS ? node.js 的应用采用的commonjs模块规范. 每一个文件就是一个模块, ...

  8. 封装成vla函数_第四章:Python之函数

    第一节:函数入门与定义函数 理解函数 所谓函数,就是为一段实现特定功能的代码"取"个名字,以后即可通过该名字来执行(调用)这段代码 从逻辑上看,函数相当于一个黑匣子 定义函数的语法 ...

  9. sigmoid函数_常用的激活(激励)函数——深度学习笔记(建议收藏)

    激活函数(又叫激励函数,后面就全部统称为激活函数)是模型整个结构中的非线性扭曲力,神经网络的每层都会有一个激活函数.那他到底是什么,有什么作用?都有哪些常见的激活函数呢? 深度学习的基本原理就是基于人 ...

最新文章

  1. PyTorch 1.8来了!正式支持AMD GPU,炼丹不必NVIDIA
  2. numpy.where用法详解,对2维数组判断解释的比较清楚的
  3. python小游戏代码大全-Python小游戏之300行代码实现俄罗斯方块
  4. BI-LSTM and CRF using Keras
  5. [剑指offer]面试题第[53-1]题[JAVA][在排序数组中查找数字-1][二分法][暴力法]
  6. 随机二次元图片API源码
  7. 录音权限 推送_友邻正式推出Linux版本录音系统
  8. linux上svn的使用教程,Linux上SVN的搭建使用
  9. 联想提取exe文件中的bios文件_3900不带X能干过99K吗?品牌机做视频渲染可以?联想刃7000P评测...
  10. 3.Java垃圾回收机制面试题
  11. csdn怎样注册?不想用微信
  12. day12 函数高级
  13. 引入element组件插件
  14. 诛仙2服务器不显示列表,诛仙2 服务器列表
  15. IDEA编译错误PersistentEnumerator storage corrupted
  16. SAP中 关于BAPI_MATERIAL_SAVEDATA创建物料报错:字段MARA-MEINS/BAPI_MARA-BASE_UOM(_ISO)被定义为必需的字段; 它不包含条目
  17. 不只Keep、FITURE、乐刻,运动健身赛道近5年吸金633亿早已起飞
  18. Oracle PLSQL 读文件与写文件
  19. Linux编译器-gcc/g++的使用
  20. 响应式织梦模板风景摄影写真类网站

热门文章

  1. python读取nc文件并转换成csv_如何使用Python读取NetCDF文件并写入CSV
  2. Constructor vs Object
  3. Retrofit2源码分析(一)
  4. 关于c:if没有c:else解决方案
  5. Windows 命令行改主机名、加域、退域、更改IP
  6. JavaScript实现限制文件上传类型和大小
  7. 都有数据一直报空指针_C语言指针难吗?纸老虎而已,纯干货讲解(附代码)...
  8. pgp 私钥需要什么样的保护措施_网络货运作为物流行业的掌舵者企业申报需要满足的条件重点有哪些...
  9. Java基础---继承
  10. redis key/value 前面出现\xac\xed\x00\x05t\x00\x06 已解决