我无法猜出真正的术语(多个相等运算符或其他),但样本在这里:
UPDATE Account
SET @newOverall = Overall = Overall - @Amount
FROM Account WHERE Id = @accountId
@newOverall = 整体 = 整体 - @Amount
是否方便TSql(在Microsoft Sql Server上)
修改
这两个答案似乎都是正确的。 (感谢Vladimir和M.Ali)如果你的表包含Trigger,你需要获得标量值,那么Vladimir的方式会更好(更安全)。如果您的更新影响多个记录,并且您需要获得所有更改的记录,而不是M.Ali的方式是赢家。但我必须选择M.Ali的方式,因为我认为OUTPUT是为这种情况创建的,它是更通用的解决方案。感谢测试代码弗拉基米尔。 (Stackoverflow我们需要多个接受的答案!:))
答案 0 :(得分:2)
KISS (保持简单Sugar)您可以在UPDATE语句中使用OUTPUT子句做类似的事情......
DECLARE @TABLE TABLE(Overall INT)
UPDATE Account
SET Overall = Overall - @Amount
OUTPUT inserted.Overall INTO @TABLE(Overall)
WHERE Id = @accountId
您的Insert语句将类似于
INSERT INTO [Transaction]
SELECT @date,@accountId,@Amount,Overall
FROM @Table
答案 1 :(得分:2)
您指定的语法完全有效并且可以正常工作,但为了避免混淆,我会将其修改为此。
UPDATE Account
SET Overall = Overall - @Amount
,@newOverall = Overall - @Amount
FROM Account
WHERE Id = @accountId
请注意,@newOverall
变量仅反映最后指定的值。如果您更新了超过1行,这将导致您遇到问题。
这是一个测试,两种方法都返回相同的结果。
DECLARE @newOverall INT
,@Amount INT = 1;
DECLARE @Account TABLE ( Overall INT )
INSERT INTO @Account
VALUES ( 10 ),
( 15 ),
( 13 )
UPDATE @Account
SET Overall = Overall - @Amount
,@newOverall = Overall - @Amount
FROM @Account
SELECT *
FROM @Account;
SELECT @newOverall
DELETE FROM @Account
INSERT INTO @Account
VALUES ( 10 ),
( 15 ),
( 13 );
UPDATE @Account
SET @newOverall = Overall = Overall - @Amount
FROM @Account
SELECT *
FROM @Account;
SELECT @newOverall;