Concat字段值在SQL Server中string

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

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

返回“John,Jim,Bob”。

我怎么能在SQL Server中做到这一点?

谢谢

实际的答案是:

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

这里常见的问题 一些search:

  • FOR XML PATH

  • concat行csv [sql-server]

尝试这个:

 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 

这样你就可以从SQL Server 2005开始

 SELECT P.ProductId, STUFF ( ( SELECT ',' + ModelThisFits FROM ModelProductFits M WHERE M.ProductId = P.ProductId ORDER BY ModelThisFits FOR XML PATH('') ), 1, 1, '' ) AS Models FROM Product P 

AFAIK,你需要自己做。

您可以构build一个用户定义的函数,该函数使用游标来循环状态为CA的Employeelogging,并返回其名称的拼接。

  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 

我从这个链接得到了这个查询

请参阅此链接了解更多说明

尝试这个

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