程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> SQL SERVER UPDATE的賦值次序

SQL SERVER UPDATE的賦值次序

編輯:關於SqlServer

1) 先變量再字段

SET NOCOUNT ON;

DECLARE @i INT, @j INT
DECLARE @Table TABLE
(
Id1 INT,
Id2 INT
);

INSERT @Table(Id1, Id2)
SELECT 1, 10
UNION ALL
SELECT 2, 20
UNION ALL
SELECT 3, 30;

SELECT @i = 1, @j = 0
UPDATE @Table SET Id1 = @i, Id2 = Id1, @i = @i + 1
SELECT * FROM @Table

SELECT @i = 1, @j = 0
UPDATE @Table SET Id1 = @i, Id2 = @j, @j = @i + 10, @i = @i + 1
SELECT * FROM @Table

SET NOCOUNT OFF;
結果:
Id1 Id2 
----------- -----------
2 1
3 2
4 3

Id1 Id2 
----------- -----------
2 11
3 12
4 13


2) 變量之間, 從左到右

SET NOCOUNT ON;

DECLARE @i INT, @j INT
DECLARE @Table TABLE
(
Id1 INT,
Id2 INT
);

INSERT @Table(Id1, Id2)
SELECT 1, 10;

SELECT @i = 1, @j = 0
UPDATE @Table SET @j = @i, @i = @i + 1
PRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)

SELECT @i = 1, @j = 0
UPDATE @Table SET @i = @i + 1, @j = @i
PRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)

SELECT @i = 1, @j = 0
UPDATE @Table SET @i = @j + 1, @j = @i
PRINT '@i = ' + CAST(@i AS VARCHAR) + ', @j = ' + CAST(@j AS VARCHAR)

SELECT @i = 1, @j = 0
UPDATE @Table SET @i = @j, @j = @i
PRINT '@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, 10
UNION ALL
SELECT 2, 20
UNION ALL
SELECT 3, 30;

UPDATE @Table SET Id1 = Id2, Id2 = Id1
SELECT * FROM @Table

SET NOCOUNT OFF;
結果:
Id1 Id2 
----------- -----------
10 1
20 2
30 3

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved