retrive逗号分隔值
我有一个名为SerialNos有以下的列表: 标识,PARENT_ID,的SerialNoretrive逗号分隔值
在PARENT_ID 像有不同的SerialNo:
Id Parent_Id SerialNo
1 16 abc
2 16 def
3 23 hij
4 23 klm
5 23 nop
我只想检索逗号分隔的SerialNos。对于特定的Parent_Id ,例如如果Parent_Id通过了16,那么O/p应该是:'abc,def' ,如果Parent_Id通过23,那么O/p应该是:'hij,klm,nop'
根据数据库服务器可以使用group_concat。例如,如果你正在使用带有“,”分隔符的mysql group_concat,将会给你你后面的结果。 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
如果您正在使用不同的数据库服务器检查其文档,它可能会有类似的东西。请记住,有些数据库没有这个功能。
对不起,只是看到您的文章被标记为sql-server2008。如果sql server 2008没有group_concat或类似的东西尝试此链接 http://blog.shlomoid.com/2008/11/emulating-mysqls-groupconcat-function.html
对不起又一次编辑,这将有所帮助。 http://groupconcat.codeplex.com/
为SQL 2008服务器可以使用下面的查询(与你的表名):
select distinct STUFF(ISNULL((SELECT ', ' + x.SerialNo
FROM TableA x
WHERE x.Parent_Id= t.Parent_Id
GROUP BY x.SerialNo
FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '')
from TableA t
where Parent_Id = 16
那么我可以指点我的博客后here,但不幸的是它不在英国:)。 Here是类似的,只是没有CLR。 有我知道至少4个解决方案:
- CLR分组功能(当然,code是英文)
- 可使用光标(不是非常快)
- 可以使用类似游标
- 可以使用XML
所以一个解决方案(不是最快的,但容易写):
Create Function fn_MyFunction
(
@Parent_Id int
)
Returns NVarChar(1000)
As
Begin
Declare @txt NVarChar(1000)
SELECT @txt = COALESCE(@txt + ';' + SerialNo, SerialNo)
FROM dbo.Table Where Parent_Id = @Parent_Id
Return @txt
End
可能重复的[基于ID的连接值](http://stackoverflow.com/questions/6603319/concatenate-values-based-on-id) – 2012-03-06 10:18:37