问题
my Column is like this:
col1
Mary
Jack
John
and i need to get something like this: Mary,Jack,John
I did it by using "For XML PATH", but the problem is that segment not work in SQL server view, is there other way to get concatenation of one column?
回答1:
try using SQL COALESCE experession to convert your column values into a comma separated string.
here's what you need to do.
DECLARE @test TABLE (
SampleCol varchar(50)
)
INSERT INTO @Test
VALUES ('Test')
INSERT INTO @Test
VALUES ('Test 1')
INSERT INTO @Test
VALUES ('Test 2')
INSERT INTO @Test
VALUES ('Test 3')
INSERT INTO @Test
VALUES ('Test 4')
DECLARE @aa varchar(200)
SET @aa = ''
SELECT
@aa =
COALESCE(CASE
WHEN @aa = '' THEN SampleCol
ELSE @aa + ',' + SampleCol
END
, '')
FROM @test
SELECT
@aa
here's a complete SQLFIDDLE
回答2:
Try this:
DECLARE @tbl TABLE(col1 VARCHAR(10));
INSERT INTO @tbl VALUES('Mary'),('Jack'),('John');
SELECT
STUFF
(
(
SELECT ', ' + col1
FROM @tbl
FOR XML PATH('')
)
,1,2,'')
来源:https://stackoverflow.com/questions/31351437/concatenate-values-of-one-column-to-single-text