sql中concat函数_SQL中的CONCAT函数概述和示例

sql中concat函数

In this article, we will explore the syntax, working mechanism and other details of the CONCAT function in SQL and we will also make up various different examples about it.

在本文中,我们将探讨SQL中CONCAT函数的语法,工作机制和其他细节,并且还将组成各种有关它的示例。

介绍 (Introduction )

A string is a set of characters that helps to declare the texts in the programming languages. In terms of SQL Server, we can categorize SQL string data types into different two groups. These are:

字符串是一组字符,有助于以编程语言声明文本。 在SQL Server方面,我们可以将SQL字符串数据类型分为不同的两组。 这些是:

  • Character strings data types that store non-Unicode character data

    存储非Unicode字符数据的字符串数据类型

    Character strings data types

    Data type

    Min limit

    Max limit

    char

    0 chars

    8000 chars

    varchar

    0 chars

    8000 chars

    varchar (max)

    0 chars

    2^31 chars

    text

    0 chars

    2,147,483,647 chars

    字符串数据类型

    数据类型

    最低限度

    最高限额

    烧焦

    0个字符

    8000个字符

    varchar

    0个字符

    8000个字符

    varchar(最大值)

    0个字符

    2 ^ 31个字符

    文本

    0个字符

    2,147,483,647字符

  • Unicode character strings data types that store Unicode character data

    存储Unicode字符数据的Unicode字符串数据类型

    Unicode character string data types

    Data type

    Min limit

    Max limit

    nchar

    0 chars

    4000 chars

    nvarchar

    0 chars

    4000 chars

    ntext

    0 chars

    1,073,741,823 char

    Unicode字符串数据类型

    数据类型

    最低限度

    最高限额

    nchar

    0个字符

    4000个字符

    nvarchar

    0个字符

    4000个字符

    文字

    0个字符

    1,073,741,823字符

We have to take into account one point about the text and ntext data types. These data types are deprecated, and for this reason, we should try not to use these data types. We can use nvarchar(max) or varchar(max) instead.

我们必须考虑到有关textntext数据类型的一点。 这些数据类型已被弃用,因此,我们应尽量不要使用这些数据类型。 我们可以使用nvarchar(max)varchar(max)代替。

SQL string functions are used to manipulate the character expressions or to obtain various information about them. CONCAT function in SQL is one of the most useful members of these functions. CONCAT function is a SQL string function that provides to concatenate two or more than two character expressions into a single string. Now, we will go into the point with a simple example.

SQL字符串函数用于操纵字符表达式或获取有关它们的各种信息。 SQL中的CONCAT函数是这些函数中最有用的成员之一。 CONCAT函数是一个SQL字符串函数,可将两个或两个以上的字符表达式连接成一个字符串。 现在,我们将通过一个简单的例子来说明这一点。

CONCAT函数语法 (CONCAT function syntax)

The syntax of the function looks like as follows:

该函数的语法如下所示:

CONCAT ( string_value1, string_value2 [, string_valueN ] )

CONCAT(string_value1,string_value2 [,string_valueN])

The CONCAT function at least requires two parameters and this function can accept a maximum of 254 parameters.

CONCAT函数至少需要两个参数,并且该函数最多可以接受254个参数。

CONCAT功能示例 (CONCAT function examples)

In this example, we will join Think and green strings with the CONCAT function:

在此示例中,我们将使用CONCAT函数将Thinkgreen字符串连接在一起:

SELECT CONCAT('Think','green') AS 'FullString'

Example of the CONCAT function in SQL

As we can see clearly in this first example, the CONCAT function joined these two strings and we obtained the Thinkgreen string.

正如我们在第一个示例中可以清楚地看到的那样,CONCAT函数将这两个字符串连接在一起 ,我们获得了Thinkgreen字符串。

In this second example, we will join 7 strings:

在第二个示例中,我们将连接7个字符串:

SELECT CONCAT('If' , ' you' , ' save', ' a', ' tree' , ' you' , ' save' ,' a' ,' life') AS 'FullString'

Usage of the CONCAT function in SQL with multiple parameter

In this second example, the CONCAT function concatenated more than two strings and the result was If you save a tree you save a life.

在第二个示例中,CONCAT函数连接了两个以上的字符串,结果是如果保存一棵树,则可以挽救生命

In addition, we can concatenate the variables with this function:

另外,我们可以使用以下函数来连接变量:

DECLARE @Str1 AS VARCHAR(100)='Think'
DECLARE @Str2 AS VARCHAR(100)='-'
DECLARE @Str3 AS VARCHAR(100)='green'
 
SELECT CONCAT(@Str1,@Str2,@Str3) AS ResultString

Usage of the CONCAT function in SQL with variables

在SQL中用CONCAT函数连接数值表达式 (Concatenating numerical expressions with CONCAT function in SQL)

CONCAT function also has the capability to join the numeric values. In the following example, we will join three different integer values:

CONCAT函数还具有连接数值的功能。 在下面的示例中,我们将连接三个不同的整数值:

SELECT CONCAT(11,33,99) AS Result

Usage of the CONCAT function for numeric values

As we can see, we did not use any CAST or CONVERT function to join these numerical expressions with the function. On the other hand, if we want to concatenate these expressions with (+) plus sign, we need to convert them to string data types. Otherwise, the result of the concatenation operation will be incorrect:

如我们所见,我们没有使用任何CAST或CONVERT函数将这些数值表达式与该函数连接。 另一方面,如果要将这些表达式与( + )加号连接起来,则需要将它们转换为字符串数据类型。 否则,串联操作的结果将不正确:

SELECT CAST(11 AS VARCHAR(10)) + CAST(33 AS VARCHAR(10)) +CAST(99 AS VARCHAR(10)) AS TrueResult

Concatenate numerical values with a plus sign

The following example demonstrates the concatenating numerical expressions with (+) plus without any data conversion so the output will be a mathematical addition:

下面的示例演示了带( + )加号的串联数字表达式,无需任何数据转换,因此输出将是数学加法:

SELECT 11+33+99 AS WrongResult

Concatenate numerical values with a plus sign without data conversion.

Now, let’s research and try to understand what is happening behind the scene while the numerical expressions concatenation process with CONCAT function.

现在,让我们研究并尝试理解在使用CONCAT函数将数值表达式连接过程中,幕后发生的事情。

Firstly, we will create a test table in order to insert some numerical expressions. The following script will create a Test_NumericValue table:

首先,我们将创建一个测试表以插入一些数字表达式。 以下脚本将创建一个Test_NumericValue表:

DROP TABLE IF EXISTS Test_NumericValue
CREATE TABLE Test_NumericValue (Number_1 INT , Number_2 INT , Number_3 INT)

In the second step, we will insert test data to this table:

在第二步中,我们将测试数据插入到此表中:

INSERT INTO Test_NumericValue VALUES (11,33,99)

Now, we will execute the below SELECT statement in the ApexSQL Plan:

现在,我们将在ApexSQL计划中执行以下SELECT语句:

SELECT CONCAT(Number_1,Number_2,Number_3) FROM Test_NumericValue

Generating execution plan of the CONCAT function in SQL

In this step, we will analyze the actual execution plan details of the query. The reason why we analyze the execution plan is that all details about the query processing operation are hidden in it:

在这一步中,我们将分析查询的实际执行计划详细信息。 我们分析执行计划的原因是有关查询处理操作的所有详细信息都隐藏在其中:

Execution plan of the CONCAT function in SQL

Let us briefly explain the query plan mentioned above. The table scan operator indicates that the query optimizer is required to read whole data of the Test_NumericValue because it does not contain any index. However, this isn’t a problem for this table because it contains only one row. On the other hand, if we find out this operator for any table which has a huge number of rows, this situation may indicate a performance issue. Compute Scalar operator performs a scalar computation and takes the task of completing the CONCAT function operation for this query execution. In the final step of the execution plan, the SELECT operator represents the result of the query. A warning sign shows on the SELECT operator. We will mention the details of this warning sign in the following tip. Now, we will click the Operations tab to find out more details about the Compute Scalar operator.

让我们简要说明上述查询计划。 表扫描运算符指示查询优化器需要读取Test_NumericValue的整个数据,因为它不包含任何索引。 但是,对于此表来说这不是问题,因为它仅包含一行。 另一方面,如果我们为具有大量行的任何表找到此运算符,则这种情况可能表示性能问题。 “计算标量”运算符执行标量计算,并承担完成此查询执行的CONCAT函数操作的任务。 在执行计划的最后一步,SELECT运算符表示查询的结果。 SELECT运算符上显示一个警告标志。 我们将在以下提示中提及此警告标志的详细信息。 现在,我们将单击“ 操作”选项卡以查找有关“计算标量”运算符的更多详细信息。

Find out the implicit conversion in CONCAT function

As we can clearly see, a data conversion occurred while the query was executing. Particularly for this query, the integer (INT) data type expressions are converted to strings (VARCHAR). With this example, we demonstrated that the data conversion operation is made by the CONCAT function. In the following tip, we will highlight another issue about the execution plan that is CONVERT_IMPLICIT operation.

我们可以清楚地看到,在执行查询时发生了数据转换。 特别是对于此查询,整数(INT)数据类型表达式将转换为字符串(VARCHAR)。 在此示例中,我们证明了数据转换操作是由CONCAT函数完成的。 在以下技巧中,我们将重点介绍有关执行计划的另一个问题,即CONVERT_IMPLICIT操作。

Tip: CONCAT function in SQL performs implicit conversion if any non-string data type parameter passes.

提示:如果传递任何非字符串数据类型参数,则SQL中的CONCAT函数将执行隐式转换。

As we mentioned above, there is a warning sign shown on the SELECT operator in the execution plan. The reason for this sign is that if we use any non-character parameters in the CONCAT function, these parameters will be converted into the string data type automatically by SQL Server. Then the string combining operation will be performed. Now, we will reinforce this theoretical information with an example:

如上所述,执行计划中的SELECT运算符上显示一个警告标志。 出现此符号的原因是,如果我们在CONCAT函数中使用任何非字符参数,则这些参数将由SQL Server自动转换为字符串数据类型。 然后将执行字符串合并操作。 现在,我们将通过一个示例来加强这一理论信息:

Firstly, we will execute the following query in order to prepare the test environment:

首先,我们将执行以下查询以准备测试环境:

DROP TABLE IF EXISTS PhoneNumbers
 
CREATE TABLE PhoneNumbers (ClientName VARCHAR(100),AreaCode INT , PhoneNumber BIGINT,Dt DATETIME)
 
INSERT INTO PhoneNumbers VALUES('Name-1',301,2929420,GETDATE())
INSERT INTO PhoneNumbers VALUES('Name-1',925,5781725,GETDATE())
INSERT INTO PhoneNumbers VALUES('Name-3',207,3188796,GETDATE())

The following query will try to concatenate 4 different data typed expressions. These are VARCHAR, INT, BIGINT, and DATETIME.

以下查询将尝试连接4个不同的数据类型表达式。 这些是VARCHARINTBIGINTDATETIME

Now, we will execute the following query:

现在,我们将执行以下查询:

SELECT CONCAT(ClientName,AreaCode,PhoneNumber,Dt) AS Result FROM PhoneNumbers

Joining the different data types with CONCAT function

As we can see, all expressions with different data types are concatenated without any error. Now, we will analyze the execution plan of the query:

如我们所见,所有具有不同数据类型的表达式被串联在一起而没有任何错误。 现在,我们将分析查询的执行计划:

CONCAT function query execution plan

When we hover the cursor on the SELECT operator icon, a pop-up window appears and the implicit conversion issue is showing obviously. Implicit conversion is a data conversion operation that is made by SQL Server automatic when it required. In addition, you can look at the Implicit conversion in SQL Server article to learn more details about the implicit conversion notion.

当我们将光标悬停在SELECT运算符图标上时,将出现一个弹出窗口,并且隐式转换问题也很明显。 隐式转换是SQL Server在需要时自动进行的数据转换操作。 此外,您可以查看SQL Server中的隐式转换文章,以了解有关隐式转换概念的更多详细信息。

SQL中的NULL值和CONCAT函数 (NULL value and CONCAT function in SQL)

NULL is a special pointer that identifies the value that is unknown or does not exist in SQL Server. In terms of CONCAT function, if we use a NULL value as a parameter to CONCAT function, it converts the NULL values to an empty string. Now, we will make an example of it:

NULL是一个特殊的指针,用于标识SQL Server中未知或不存在的值。 就CONCAT函数而言,如果我们将NULL值用作CONCAT函数的参数,则它将NULL值转换为空字符串。 现在,我们将举一个例子:

SELECT CONCAT('Think' , NULL , 'green') AS 'FullString'

CONCAT function in SQL and NULL value

As we can see, the NULL expression used in the CONCAT function did not affect the result of the function and behaved like an empty string. In addition, if we pass all parameters as NULL, the result of the function will be an empty string. Now, we will make an example of this:

如我们所见,CONCAT函数中使用的NULL表达式不影响该函数的结果,其行为类似于空字符串。 另外,如果我们将所有参数都传递为NULL 则函数的结果将为空字符串。 现在,我们将举一个例子:

SELECT CONCAT(NULL , NULL , NULL) AS 'FullString'

As a result, we can say that NULL values do not affect the output of the function.

结果,我们可以说NULL值不影响函数的输出。

如何在CONCAT函数中使用换行(\ n)和回车(\ r) (How to use line feed (\n) and carriage return (\r) with CONCAT function)

CHAR function enables to convert ASCII numbers to character values. The following ASCII codes can be used to get a new line with CHAR function in SQL:

焦炭 函数可以将ASCII数字转换为字符值。 以下ASCII代码可用于在SQL中使用CHAR函数获取新行:

Value

Char

Description

10

LF

Line Feed

13

CR

Carriage Return

烧焦

描述

10

如果

换行

13

CR

回车

We can get a new line when we concatenate the strings with the following CHAR functions:

当使用以下CHAR函数将字符串连接在一起时,我们可以换行:

  • CHAR (10): New Line / Line Feed CHAR(10):新行/换行
  • CHAR (13): Carriage Return CHAR(13):回车

For example, the following query results in the concatenated string line by line with CHAR(13) function:

例如,以下查询使用CHAR(13)函数逐行生成连接的字符串:

SELECT CONCAT('Make',CHAR(13),'every' ,CHAR(13),'drop' , CHAR(13) , 'of',CHAR(13),'water',CHAR(13),
'count') AS Result

CONCAT function usage with CHAR(13)

Now, we will replace CHAR(13) expression with CHAR(10) expression and re-execute the same query:

现在,我们将CHAR(13)表达式替换为CHAR(10)表达式,然后重新执行相同的查询:

SELECT CONCAT('Make',CHAR(10),'every' ,CHAR(10),'drop' , CHAR(10) , 'of',CHAR(10),'water',CHAR(10),
'count') AS Result

CONCAT function usage with CHAR(10)

At the same time, we can use CHAR(13) and CHAR(10) together. This usage type could be a good option when we want to generate a line break. Now, we will make a demonstration of it:

同时,我们可以一起使用CHAR(13)CHAR(10) 。 当我们要生成换行符时,此用法类型可能是一个不错的选择。 现在,我们将对其进行演示:

SELECT CONCAT('Make',CHAR(10),CHAR(13),'every' ,CHAR(10),CHAR(13),'drop' , CHAR(10),CHAR(13) 
, 'of',CHAR(10),CHAR(13),'water',CHAR(10),CHAR(13),
'count') AS Result
CONCAT function usage with CHAR(13) and CHAR(10)

结论 (Conclusion)

In this article, we have learned the CONCAT function in SQL using various examples. CONCAT function is a very useful option to concatenate the expressions in the SQL.

在本文中,我们通过各种示例学习了SQL中的CONCAT函数。 CONCAT函数是连接SQL中的表达式的非常有用的选项。

翻译自: https://www.sqlshack.com/an-overview-of-the-concat-function-in-sql-with-examples/

sql中concat函数

  • 2
    点赞
  • 0
    评论
  • 4
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值