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'

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'

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

在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

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

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

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

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:

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

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运算符上显示一个警告标志。 我们将在以下提示中提及此警告标志的详细信息。 现在,我们将单击“ 操作”选项卡以查找有关“计算标量”运算符的更多详细信息。

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 PhoneNumbersCREATE 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

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:

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

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'

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

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

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

结论 (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函数

sql中concat函数_SQL中的CONCAT函数概述和示例相关推荐

  1. java中rank函数_sql rank()函数

    RANK() OVER([]) partition_by_clause 将from子句生成的结果集划分为应用到RANK函数的分区. Order_by_clause确定将RANK值应用到分区中的行时所使 ...

  2. java中rank函数_SQL中的排名函数(ROW_NUMBER、RANK、DENSE_RANK、NTILE)简介

    排名函数是Sql Server2005新增的功能,下面简单介绍一下他们各自的用法和区别. 在使用排名函数的时候需要注意以下三点: 1.排名函数必须有 OVER 子句. 2.排名函数必须有包含 ORDE ...

  3. sql中聚合函数和分组函数_SQL选择计数聚合函数-语法示例解释

    sql中聚合函数和分组函数 The COUNT operator is usually used in combination with a GROUP BY clause. It is one of ...

  4. mysql sql查询json数据类型_SQL中的JSON数据类型

    SQL中的JSON数据类型 概述 MySQL支持原生JSON类型,使用JSON数据类型相较于将JSON格式的字符串存储在String型中的优势有: 存储时会自动验证JSON文本: 可以优化存储格式.存 ...

  5. mysql iif函数_sql中的iif语句详解_mysql

    IIf 返回由逻辑测试确定的两个数值或字符串值之一. 语法 数字 IIf(«Logical Expression», «Numeric Expression1», «Numeric Expressio ...

  6. sql 累计占比_sql中查询占百分比percent和通配符的使用

    标签: 第一.PERCENT w3cschool中不断的更新着新的知识点.有些感觉都没有这个概念,应该是几乎没有用在工作上的缘故吧如查询数据前面的一半: SELECT TOP 50 PERCENT * ...

  7. exsits函数_SQL中EXISTS的用法

    比如在Northwind数据库中有一个查询为 SELECT c.CustomerId,CompanyName FROM Customers c WHERE EXISTS( SELECT OrderID ...

  8. Java 中exists用法_sql中exists,not exists的用法

    exists : 强调的是是否返回结果集,不要求知道返回什么, 比如: select name from student where sex = 'm' and mark exists(select ...

  9. Java 中exists用法_SQL中EXISTS的用法

    比如在Northwind数据库中有一个查询为 SELECT c.CustomerId,CompanyName FROM Customers c WHERE EXISTS( SELECT OrderID ...

  10. Java choose函数_SQL SERVER 2012新增函数之逻辑函数CHOOSE详解

    SQL SERVER 2012中新增了CHOOSE,该函数可以从值列表返回指定索引处的项. 例如: select CHOOSE(3,'A','B','C','D') as R1 /* R1 ---- ...

最新文章

  1. GROMACS运行参数之nvt.mdp文件详解
  2. mysql中timestamp类型数据查找中出现的问题
  3. Mysql存储过程(四)——异常处理
  4. Springboot中进行日志打印需要的信息
  5. 诗与远方:无题(三十一)- 祝我单身
  6. gerber文件_90%的工程师容易忽视(一):PCB输出gerber文件,这样操作才正确!
  7. java实现菱形的打印java实现菱形的输出
  8. 玩转CSDN之自定义博客栏目
  9. 2020阿里云服务器免费领取与互联教程
  10. 你是怎样毁掉自己的?
  11. 【技术沙龙】星火计划 | 腾讯自研Kona JDK技术分享沙龙火热报名中
  12. 【软件需求工程与建模】13组组队项目小组分工及当前完成的工作
  13. 对Livox_avia内置IMU-BMI088进行内参标定
  14. 解决欠拟合和过拟合的几种方法
  15. Airport Simulation (数据结构与算法 – 队列 / Queue 的应用)
  16. 域适应(DA)---域泛化(DG)
  17. 彩色激光同轴位移计在点胶行业的应用(胶水测量)
  18. 国内外主要射频器件厂商介绍
  19. 产业区块链一周动态丨新四板跑步上链,国家区块链漏洞库定级细则发布
  20. 图片涂鸦html插件,HTML5 canvas 在线涂鸦

热门文章

  1. 用PS自己制作一寸证件照照片
  2. 动软出现“添加服务器配置失败,请检查是否有写入权限或文件是否存在“错误
  3. PCB覆铜利弊——天线角度
  4. ansys--workbench(导入solidworks)受力分析
  5. 随机排列算法(Fisher-Yates)
  6. matlab上的派克变换变换,Matlab_Simulink中Clark变换和Park变换的深度总结
  7. cpu使用率的另一种获取方法
  8. HTML特效文字代码大全
  9. Android 获取文件后缀名
  10. 《Arduino》开发 之 用 u8g2 库 给 0.96寸OLED 刷bmp图片,OLED图片取模