How to concatenate in SQL Server

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 14:52:44

问题


My database doesn't have a specific column so I created a column in my query by 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

回答1:


To concatenate strings in SQL Server you can simply use the + operator.
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.

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). this means that if certificateDurationType is not 0, 1 or 2 the case statement will return null.




回答2:


You just need to try + operator or CONCAT function

  1. + for all SQL Server versions

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

    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


来源:https://stackoverflow.com/questions/30011871/how-to-concatenate-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!