这个问题说来惭愧,我以前遇到这样一个问题:
更新表A时,需要用到表A自身且字段也是同一字段,如何区分呢?
还有更新一个表变量@tb时,我们需要给表变量的某一字段指定所属表,但是我们显然不能使用@tb,这时怎么办呢?
一直以来用到都是比较笨的办法,直到无意间发现Update也可用别名。
这也让我一下明白了,sql的解析是从From开始的。
1 DECLARE @tb TABLE
2 (
3 OID INT,
4 vName NVARCHAR(50),
5 dcQty DECIMAL(15, 2)
6 )
7
8 INSERT INTO @tb ( OID, vName, dcQty )
9 VALUES ( /* OID - INT */ 1,
10 /* vName - NVARCHAR(50) */ N'aa',
11 /* dcQty - DECIMAL(15, 2) */ 2 )
12
13 INSERT INTO @tb ( OID, vName, dcQty )
14 VALUES ( /* OID - INT */ 2,
15 /* vName - NVARCHAR(50) */ N'bb',
16 /* dcQty - DECIMAL(15, 2) */ 4 )
17
18 INSERT INTO @tb ( OID, vName, dcQty )
19 VALUES ( /* OID - INT */ 2,
20 /* vName - NVARCHAR(50) */ N'bb',
21 /* dcQty - DECIMAL(15, 2) */ 3 )
22
23 INSERT INTO @tb ( OID, vName, dcQty )
24 VALUES ( /* OID - INT */ 3,
25 /* vName - NVARCHAR(50) */ N'cc',
26 /* dcQty - DECIMAL(15, 2) */ 6 )
27
28 UPDATE T1
29 SET T1.dcQty = T2.dcQty
30 FROM @tb AS T1
31 JOIN ( SELECT OID,
32 SUM(dcQty) AS dcQty
33 FROM @tb
34 GROUP BY OID
35 ) AS T2 ON T1.OID = T2.OID
36
37 SELECT *
38 FROM @tb
39
2 (
3 OID INT,
4 vName NVARCHAR(50),
5 dcQty DECIMAL(15, 2)
6 )
7
8 INSERT INTO @tb ( OID, vName, dcQty )
9 VALUES ( /* OID - INT */ 1,
10 /* vName - NVARCHAR(50) */ N'aa',
11 /* dcQty - DECIMAL(15, 2) */ 2 )
12
13 INSERT INTO @tb ( OID, vName, dcQty )
14 VALUES ( /* OID - INT */ 2,
15 /* vName - NVARCHAR(50) */ N'bb',
16 /* dcQty - DECIMAL(15, 2) */ 4 )
17
18 INSERT INTO @tb ( OID, vName, dcQty )
19 VALUES ( /* OID - INT */ 2,
20 /* vName - NVARCHAR(50) */ N'bb',
21 /* dcQty - DECIMAL(15, 2) */ 3 )
22
23 INSERT INTO @tb ( OID, vName, dcQty )
24 VALUES ( /* OID - INT */ 3,
25 /* vName - NVARCHAR(50) */ N'cc',
26 /* dcQty - DECIMAL(15, 2) */ 6 )
27
28 UPDATE T1
29 SET T1.dcQty = T2.dcQty
30 FROM @tb AS T1
31 JOIN ( SELECT OID,
32 SUM(dcQty) AS dcQty
33 FROM @tb
34 GROUP BY OID
35 ) AS T2 ON T1.OID = T2.OID
36
37 SELECT *
38 FROM @tb
39