concatenate values of one column to single text

北城余情 提交于 2019-12-25 04:15:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!