-8

I would like to know how to concatenate two different values from two different columns from a SQL table using TSQL ?

enter image description here

As you can see, I would like to concatenate those two different columns X e Y, resulting in the follow column table:

enter image description here

Which query should be used here ?

P.Salmon
  • 17,104
  • 2
  • 12
  • 19
Yan
  • 105
  • 7

3 Answers3

1

if the datatype is numeric types(int,bigint, tinyint,smallint,etc) then you need to cast it to string before you concatenate. if the datatype is string(varchar,char,nvarchar,nchar) then you can directly use concat function

select concat(cast(column_1 as varchar) ,cast(column_2 as varchar))

select concat(column_1,column_2)

another workaround, if the columns are string datatype, then

select column_1+column_2

sample

with cte as (select 1 as id, 'name' as Field1, 'job' as Field2, '1test1' as Field1value , '2test1' as Field2value 
union select 2 as id, 'name' as Field1, 'job' as Field2, '1test1' as Field1value , '2test2' as Field2value 
union select 2 as id, 'age' as Field1, 'town' as Field2, '13' as Field1value , 'town1' as Field2value )
select 'select percentage from table2 where '+Field1+' ='+ ''''+Field1value+ ''''+' and '+Field2+' = '+  ''''+Field2value+ '''' from cte

result

enter image description here

Note: null value in any one column will have result as null

Moulitharan M
  • 729
  • 4
  • 15
0

You can simply use + to concatenate charcaters.

Query

select *, x + ',' + y as z
from your_table_name;

If there is a null value in any of the columns, then the concatenation results to a null value.

To handle the null value in any of the column

Query

select *,
case 
  when x is null and y is not null then y
  when y is null and x is not null then x
  when x is null and y is null then null
  else x + ',' + y end as z
from your_table_name;
Ullas
  • 11,450
  • 4
  • 33
  • 50
0

You can use concat as

SELECT 
    Source, QtyPrevious, QtyToday, ProductPrevious, ProductToday, 
    AvaDatePr, AvaDateToday, Clusters, CONCAT(X, '', Y) as Z 
from your_table_name;
user8193706
  • 2,387
  • 2
  • 8
  • 12