1

我的代码:

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

这返回2, 2, 2, 4,。一切都很好。

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

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

SELECT @CHARS

它返回, , , , 2224。它不应该返回, 2, 2, 2, 4吗?

4

1 回答 1

1

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

假设你有

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

让它更清楚

对于第一行,它返回", 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
于 2016-03-28T23:27:17.780 回答