Decrease Font Size
Increase Font Size
   BLOG

How to select multiple column values into a single row of string

" Parsing SQL column data into single string "

" SELECT column values into a concatenated string (SQL) "

" sql select column into single string"

" T-SQL - Select records into concatenated string" "how to combine string data from multiple columns into one column? "

Below is a simple example.

DECLARE @TempTable Table 
(
	col1 varchar(10),
	col2 char(1)
)

INSERT INTO @TempTable (col1, col2) values ('aa', 'Y')
INSERT INTO @TempTable (col1, col2) values ('bb', 'N')
INSERT INTO @TempTable (col1, col2) values ('cc', 'Y')
INSERT INTO @TempTable (col1, col2) values ('dd', 'N')
INSERT INTO @TempTable (col1, col2) values ('ee', 'N')
INSERT INTO @TempTable (col1, col2) values ('ff', 'Y')

--check table
SELECT * FROM @TempTable

DECLARE @my_long_string varchar(1000)
SET @my_long_string = ''

SELECT	@my_long_string = COALESCE(@my_long_string + ',', '') + col1
				FROM  @TempTable 
				WHERE col2 = 'Y'
				
SELECT substring(@my_long_string,CHARINDEX(',', @my_long_string)+1,len(@my_long_string))