如何列出T-SQL结果以及它们之间的逗号? [英] How to make a list of T-SQL results with comma's between them?
本文介绍了如何列出T-SQL结果以及它们之间的逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个简单的查询,像这样:
Suppose we have a simple query like this:
SELECT x
FROM t
WHERE t.y = z
如果结果集中有一条记录,我想设置变量 @v
到那个值。如果我们有两个或多个记录,我希望结果用逗号和空格分隔。编写此T-SQL代码的最佳方法是什么?
If we have one record in the result set, I want to set variable @v
to that one value. If we have two or more records, I'd like the results to be separated by a comma and a space. What is the best way to write this T-SQL code?
示例:
结果集1条记录:
Value1
2条记录的结果集:
Value1, Value2
结果集3条记录:
Value1, Value2, Value3
推荐答案
这将为您提供以下值的列表逗号分隔的列表
this will give you the list of values in a comma separated list
create table #temp
(
y int,
x varchar(10)
)
insert into #temp values (1, 'value 1')
insert into #temp values (1, 'value 2')
insert into #temp values (1, 'value 3')
insert into #temp values (1, 'value 4')
DECLARE @listStr varchar(255)
SELECT @listStr = COALESCE(@listStr+', ', '') + x
FROM #temp
WHERE #temp.y = 1
SELECT @listStr as List
drop table #temp
这篇关于如何列出T-SQL结果以及它们之间的逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文