把某一列值转换为逗号分隔字符串
问题是这样的。从订阅表中SELECT某一个用户所有订阅的目录,然后可以绑定至前台显示给用户,让用户知道自己有哪些订阅和哪些目录没有订阅。
如下表[dbo].[SubScription]:
需要SELECT用户ID为15的所有订阅目录。如最终结果:
Insus.NET是在SQL Server 2012结合XML的FOR XML PATH()来实现。参考:
View Code
SELECT [UsersId], [SubscriptionCataLog] = STUFF((SELECT ',' + CAST([SubscriptionCatalog_nbr] AS NVARCHAR(MAX))
FROM [dbo].[SubScription] WHERE ([UsersId] = s.[UsersId])
FOR XML PATH ('')),1,1,'')
FROM [dbo].[SubScription] s
WHERE [usersId] = 15
GROUP BY [UsersId]
FROM [dbo].[SubScription] WHERE ([UsersId] = s.[UsersId])
FOR XML PATH ('')),1,1,'')
FROM [dbo].[SubScription] s
WHERE [usersId] = 15
GROUP BY [UsersId]
首先是在数据表FROM [dbo].[SubScription],条件为WHERE [usersId] = 15过滤出用户所有订阅目录,并分组GROUP BY [UsersId]
然后把[SubscriptionCatalog_nbr]由整型转为字符串:CAST([SubscriptionCatalog_nbr] AS NVARCHAR(MAX)
再用','与之串连起来,最后用FOR XML PATH ('')方法,把每一行数据串连接起。
详细一些,可以看到:
SELECT ',' + CAST([SubscriptionCatalog_nbr] AS NVARCHAR(MAX))
FROM [dbo].[SubScription]
FOR XML PATH ('')
FROM [dbo].[SubScription]
FOR XML PATH ('')
执行得到的结果:
STUFF这个函数,是为了截除第一个逗号。