Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Best way to concatenate multiple columns?

I am trying to concatenate multiple columns in a query in SQL Server 11.00.3393.

I tried the new function CONCAT() but it's not working when I use more than two columns.

So I wonder if that's the best way to solve the problem:

SELECT CONCAT(CONCAT(CONCAT(COLUMN1,COLUMN2),COLUMN3),COLUMN4) FROM myTable

I can't use COLUMN1 + COLUMN2 because of NULL values.

EDIT

If I try SELECT CONCAT('1','2','3') AS RESULT I get an error

The CONCAT function requires 2 argument(s)

like image 646
D. Caan Avatar asked Jun 23 '14 16:06

D. Caan


People also ask

How do I concatenate multiple columns in SQL Server?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I combine data from multiple columns into one in SQL?

Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.

How do I concatenate all columns in SQL?

If you have SQL Server 2017 or later, using CONCAT_WS() is the best way to concatenate multiple columns to a string value. Here you have to specify the separator in the form of char, nchar, varchar or nchar as the first argument. Then you can pass on the columns to concatenate in the subsequent arguments.


2 Answers

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')
like image 72
Hart CO Avatar answered Oct 09 '22 15:10

Hart CO


SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
       INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995
like image 24
JUVA Avatar answered Oct 09 '22 14:10

JUVA