简体   繁体   English

如何在 SQL Server 中连接

[英]How to concatenate in SQL Server

My database doesn't have a specific column so I created a column in my query by switch.我的数据库没有特定的列,所以我通过 switch 在我的查询中创建了一个列。 What I need is to concatenate this column with another column in the database:我需要的是将此列与数据库中的另一列连接起来:

select 
    certificateDuration ,
   'DurationType' = case
                      when certificateDurationType = 0 then 'Day' 
                      when certificateDurationType = 1 then 'Month'
                      when certificateDurationType = 2 then 'Year'
                    end
from 
    Scientific_Certification

To concatenate strings in SQL Server you can simply use the + operator .要在 SQL Server 中连接字符串,您只需使用+ 运算符即可
Note that if one of the substrings is null then the entire concatenated string will become null as well.请注意,如果子字符串之一为空,则整个连接的字符串也将变为空。 therefor, use COALESCE if you need a result even if one substring is null.因此,如果您需要结果,即使一个子字符串为空,也请使用COALESCE

select certificateDuration,
       ' DurationType = '+ 
       COALESCE(case
                     when certificateDurationType = 0 then 'Day' 
                     when certificateDurationType = 1 then 'Month'
                     when certificateDurationType = 2 then 'Year'
                     end, '') As DurationType 
from Scientific_Certification

Note: I've used coalesce on your case clause since you have no default behavior (specified by else ).注意:由于您没有默认行为(由else指定),因此我在您的 case 子句上使用了 coalesce 。 this means that if certificateDurationType is not 0, 1 or 2 the case statement will return null .这意味着如果certificateDurationType不是 0、1 或 2,则 case 语句将返回null

You just need to try + operator or CONCAT function您只需要尝试+运算符或CONCAT函数

  1. + for all SQL Server versions +适用于所有 SQL Server 版本

    DurationType = ' + 'some text'
  2. CONCAT for SQL Server 2012 + SQL Server 2012 + CONCAT

     CONCAT('DurationType = ', 'some text')

Your query should be something like this您的查询应该是这样的

SELECT certificateDuration
       ,'DurationType = ' + 
       CASE certificateDurationType
           WHEN 0 THEN 'Day'
           WHEN 1 THEN 'Month'
           WHEN 2 THEN 'Year'
       END
FROM Scientific_Certification

you must try this SQL query to contact the columns.您必须尝试使用​​此 SQL 查询来联系列。 Here I concat three columns of user table named (name_first, name_middle, name_last) and got the result into a single column named FULLNAME.在这里,我连接了名为 (name_first, name_middle, name_last) 的用户表的三列,并将结果放入名为 FULLNAME 的单个列中。

SQL查询代码

Here is the image of result这是结果的图像

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM