我想select Column from Table
使用SQL Server 将结果返回到逗号分隔的字符串中.
有问题的列相当大(nvarchar(2000)
),因此解决方案必须能够处理非常大的结果值.
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
:
SELECT @result = @result + [Column] + N',' FROM [TABLE] WHERE [Column] IS NOT NULL
没有尾随逗号版本:
declare @s varchar(max); select @s = isnull(@s + ', ' + lastname, lastname) from person order by lastname; print @s;
在SQL 2017中添加了STRING_AGG
https://docs.microsoft.com/zh-cn/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017
SELECT STRING_AGG (ColumnName, ',') AS csv FROM TableName GROUP BY ColumnName2