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

本文详细介绍了如何在SQL Server中使用SQL Plus(+)运算符和CONCAT函数进行字符串连接操作。讨论了两者在处理NULL值、数据类型转换以及多个字段串联时的差异和注意事项,提供了丰富的示例和解决方案。
摘要由CSDN通过智能技术生成

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 Server CONCATENATE

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。

SQL Server CONCATENATE

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

SQL Server CONCATENATE

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];

Example of SQL CONCATENATE

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] e
     INNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = e.[BusinessEntityID]
WHERE p.Middlename IS NOT NULL;

Example of SQL CONCATENATE

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';

Example of SQL CONCATENATE

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''';
Example of SQL CONCATENATE
  • 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''';

Example of SQL CONCATENATE

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

SQL CONCAT

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()函数来获取连接字符串中的指定日期。

SQL CONCAT

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];

SQL CONCAT example
  • 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

CONCAT examples

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

Concat examples

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函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值