据记录,递归变量赋值(像这样↓↓↓↓)有时会返回不正确的结果:
SELECT @var = @var + [Name]
FROM dbo.People
...
但即使在我确信只返回一行的情况下这是否适用?
示例(小提琴):
CREATE TABLE dbo.People
(
Id INT IDENTITY PRIMARY KEY,
[Name] varchar(50) NOT NULL
);
INSERT INTO dbo.People([Name]) VALUES ('Bob');
DECLARE @var varchar(50) = '';
/*Is this bad even if the query always returns only one row?*/
SELECT @var = @var + [Name]
FROM dbo.People
WHERE Id = 1;
SELECT [@var] = @var;
文档说“在这种情况下,不能保证@Var会逐行更新。 ”这(对我来说)表明单行选择应该没问题,对吗?
另一个可能想要使用它的例子是计算一些聚合值并将它们添加到某个地方:
SELECT @Total = @Total + SUM(InvoiceTotal) /*single row, aggregate of several values*/
FROM dbo.Invoice
WHERE ...;
/*Notice no GROUP BY*/