SQL 字符串聚合 returns 基于变量位置的不同结果

SQL String aggregation returns different results based on location of variables

我的代码:

if object_id('tempdb..#t1') is not null drop table #t1

create table #t1 (ID int, name varchar(10))

insert into #t1 values (1,'2'), (6,'2'), (6,'2'), (1,'4')

DECLARE @CHARS VARCHAR(100) = ''
SELECT @CHARS = @CHARS + name + ', ' -- <---CODE OF INTEREST
FROM #t1

这个returns 2, 2, 2, 4,。一切顺利。

但是,当我更改上面的代码以首先附加逗号和 space 时:

DECLARE @CHARS VARCHAR(100) = ''
SELECT @CHARS = ', ' + @CHARS + name -- <---CODE OF INTEREST
FROM #t1

SELECT @CHARS

它 returns , , , , 2224。不应该return, 2, 2, 2, 4吗?

第二个公式的逻辑是:对于每条记录,它将字符串附加到@CHARS

的右侧

假设你有

insert into #t1 values (1,'2'), (6,'3'), (6,'4'), (1,'5')

为了更清楚

对于第一行来说returns", 2"

对于第二行,您的@CHARS 将是 ", " + ", 2" + "3"

对于第三行,@CHARS 是 ", , 23" 所以将 @CHARS 设置为 ", " + ", , 23" + "4"

尝试以下查询以查看发生了什么:

DECLARE @CHARS VARCHAR(100) = ''
SELECT top 1 @CHARS = ', ' + @CHARS + name -- <---CODE OF INTEREST
FROM #t1

print @CHARS
go

Result: , 2
--------------------------
DECLARE @CHARS VARCHAR(100) = ''
SELECT top 2 @CHARS = ', ' + @CHARS + name -- <---CODE OF INTEREST
FROM #t1

print @CHARS
go

Result: , , 23
----------------------
DECLARE @CHARS VARCHAR(100) = ''
SELECT top 3 @CHARS = ', ' + @CHARS + name -- <---CODE OF INTEREST
FROM #t1

print @CHARS
go
Result: , , , 234