SQL SERVER UPDATE的赋值次序
1) 先变量再字段
SET NOCOUNT ON;
DECLARE @i INT, @j INTDECLARE @Table TABLE(Id1 INT,Id2 INT);
INSERT @Table(Id1, Id2)SELECT 1, 10UNION ALLSELECT 2, 20UNION ALLSELECT 3, 30;
SELECT @i = 1, @j = 0UPDATE @Table SET Id1 = @i, Id2 = Id1, @i = @i + 1SELECT * FROM @Table
SELECT @i = 1, @j = 0UPDATE @Table SET Id1 = @i, Id2 = @j, @j = @i + 10, @i = @i + 1SELECT * FROM @Table
SET NOCOUNT OFF;结果:Id1 Id2 ----------- ----------- 213243
Id1 Id2 ----------- ----------- 211312413
2) 变量之间, 从左到右
SET NOCOUNT ON;
DECLARE @i INT, @j INTDECLARE @Table TABLE( Id1 INT, Id2 INT);
INSERT @Table(Id1, Id2)SELECT 1, 10;
SELECT @i = 1, @j = 0UPDATE @Table SET @j = @i, @i = @i + 1PRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)
SELECT @i = 1, @j = 0UPDATE @Table SET @i = @i + 1, @j = @iPRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)
SELECT @i = 1, @j = 0UPDATE @Table SET @i = @j + 1, @j = @iPRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)
SELECT @i = 1, @j = 0UPDATE @Table SET @i = @j, @j = @iPRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)
SET NOCOUNT OFF;结果:@i = 2, @j = 1@i = 2, @j = 2@i = 1, @j = 1@i = 0, @j = 0
3) 字段之间, 并行执行
SET NOCOUNT ON;
DECLARE @Table TABLE(Id1 INT, Id2 INT);
INSERT @Table(Id1, Id2)SELECT 1, 10UNION ALLSELECT 2, 20UNION ALLSELECT 3, 30;
UPDATE @Table SET Id1 = Id2, Id2 = Id1SELECT * FROM @Table
SET NOCOUNT OFF;结果:Id1 Id2 ----------- ----------- 10; 120; 230; 3