假设我们在 SQLServer-2005 中有一个包含两列和以下数据行的下表:
Tiger 50
Wolf 4
Tiger 53
Lion 55
Elephant 54
Rhino 52
Lion 5
我们可以有一个 sql 查询,其结果如下:Tiger,Wolf,Lion,Elephant,Rhino
作为单个字符串 varchar 输出?可能吗?
使用 T-SQL 不可能,我正在使用 c# 中的结果作为executescalar 的结果
预先感谢您。
最佳答案
您可以使用作为 xml 路径
来连接值:
select distinct name + ', ' as [text()]
from @t
for xml path('')
-->
Elephant, Lion, Rhino, Tiger, Wolf,
如果您不喜欢尾随 ,
,则切掉最后 2 个字节。
不知道为什么不能使用 T-SQL,您可以将其与 ExecuteScalar() 结合使用。
示例数据:
declare @t table (name varchar(max), id int)
insert into @t
select 'Tiger', 50
union all select 'Wolf', 4
union all select 'Tiger', 53
union all select 'Lion', 55
union all select 'Elephant', 54
union all select 'Rhino', 52
union all select 'Lion', 5
关于sql - 如何在sql中选择不同和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2081485/