如何在不使用游标的情况下将表的一列转换为 SQL Server 中的 csv 字符串 [英] How to turn one column of a table into a csv string in SQL Server without using a cursor
本文介绍了如何在不使用游标的情况下将表的一列转换为 SQL Server 中的 csv 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 SQL Server 将 select Column from Table
的结果返回为逗号分隔的字符串.
I want to return the results of select Column from Table
into a comma separated string using SQL Server.
有问题的列相当大 (nvarchar(2000)
),因此解决方案必须能够处理非常大的结果值.
The column in question is rather large (nvarchar(2000)
) so the solution has to be able to handle very large result values.
推荐答案
DECLARE @result nvarchar(max)
SET @result = ''
SELECT @result = @result + [Column] + N','
FROM [TABLE]
--TODO: trim last ',' if you require
PRINT @result
如果 Column
可以为 null,那么要么先排除它,要么使用 ISNULL
/COALESCE
- 否则使用单个 NULL
将破坏整个序列.使用 WHERE
:
If Column
can be null, then either exclude it first, or use ISNULL
/COALESCE
- otherwise a single NULL
will break the entire sequence. It is more efficient to exclude it with a WHERE
:
SELECT @result = @result + [Column] + N','
FROM [TABLE]
WHERE [Column] IS NOT NULL
这篇关于如何在不使用游标的情况下将表的一列转换为 SQL Server 中的 csv 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文