Concat字段值为SQL Server中的字符串

时间:2009-10-25 19:08:52

标签: sql sql-server csv concatenation

我需要一个与SQL Server中的Oracle WM_CONCAT类似的函数,它返回一个逗号分隔的列表,其中包含您作为参数传递的任何字段。例如,在Oracle中,

select WM_CONCAT(first_name) from employee where state='CA' 

返回“John,Jim,Bob”。

如何在SQL Server中执行此操作?

由于

6 个答案:

答案 0 :(得分:3)

实际答案:

SELECT
   SUBSTRING(buzz, 2, 2000000000)
FROM
    (
    SELECT 
        firstname
    FROM 
        employee
    WHERE
        State = 'CA'
    FOR XML PATH (',')
    ) fizz(buzz)

这是一个常见的问题。一些搜索:

答案 1 :(得分:2)

试试这个:


    drop table #mike_temp 
go

select * into #mike_temp 
  from (select 'Ken'  as firstname, 'CO' as state
         union all
        select 'Mike' as firstname, 'CO' as state
         union all
        select 'Tom' as firstname , 'WY' as state
       ) a
go

SELECT distinct 
       state
      ,STUFF((SELECT ', ' + b.firstname FROM #mike_temp b where a.state = b.state FOR XML PATH('')),1, 2, '') AS CSVColumn
  from #mike_temp a

答案 2 :(得分:1)

在SQL Server 2017中添加了STRING_AGG功能

SELECT t.name as TableName
      ,STRING_AGG(c.name, ';') AS FieldList
  FROM sys.tables t
  JOIN sys.columns c 
    ON t.object_id = c.object_id
  GROUP BY t.name;

答案 3 :(得分:0)

AFAIK,你需要自己做。

您可以构建一个用户定义的函数,该函数使用游标循环其中状态为CA的Employee记录并返回其名称的串联。

答案 4 :(得分:0)

 SELECT Field1, Substring(Field2, 2, LEN(Field2)) AS Field2 FROM
(
    SELECT
        [InnerData].Field1,
        (SELECT  ',' + Field2 FROM @Fields WHERE Field1=[InnerData].Field1 FOR XML PATH('')) AS Field2
        FROM
        (
            SELECT DISTINCT Field1 FROM @Fields
        ) AS [InnerData]
) AS OuterData

我从此链接

获得此查询

Refer this Link for more Clarification

答案 5 :(得分:-3)

试试这个

 select    
    wm_concat(name) 
 from
    employee
 where
    state='CA'
 group by
    state