Amer ALtahawy
Amer ALtahawy

Reputation: 43

How to concatenate in SQL Server

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

Upvotes: 2

Views: 21700

Answers (3)

Neha Soni
Neha Soni

Reputation: 4674

you must try this SQL query to contact the columns. 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.

Code for SQL query

Here is the image of result

Result

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82474

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.

Upvotes: 1

sqluser
sqluser

Reputation: 5672

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

Upvotes: 5

Related Questions