在数据库开发中经常遇到要进行多表更新的情况
,多表更新可以通过游标循环来实现
,但是要写好多语句,不太方便,因此很多人用多表更新来实现,但是如果在使用中不注意语法的严谨性,就会产生不可挽回的失误
。下面我将通过实例来进行说明
。 1、在
SQL SERVER 中 Create table A (c1 VARCHAR(10),c2 VARCHAR(10)); insert into a values('1','a1'); insert into a values('2','a2'); insert into a values('3','a3'); insert into a values('8','a8'); Create table B (c1 VARCHAR(10),c3 VARCHAR(10)); insert into b values('1','b1'); insert into b values('2','b2'); insert into b values('3','b3'); insert into b values('10','b10');
##多表更新 示例1 UPDATE A SET A.c2 =B.c3 from A ,B where A.c1=B.c1;
(所影响的行数为 3 行)
select * from a; c1 c2 ---------- ---------- 1 b1 2 b2 3 b3 8 a8
##多表更新 示例2 update a set a.c2 = (select b.c3 from b where a.c1=b.c1);
(所影响的行数为 4 行) select * from a; c1 c2 ---------- ---------- 1 b1 2 b2 3 b3 8 NULL
##多表更新 示例3 update a set a.c2 = (select b.c3 from b where a.c1=b.c1) where exists (select 1 from b where a.c1=b.c1); (所影响的行数为 3 行)
select * from a; c1 c2 ---------- ---------- 1 b1 2 b2 3 b3 8 a8
2、在
Oracle中 Create table A (c1 NUMBER(10),c2 VARCHAR(10),c4 NUMBER(1)); insert into a values(1,'a1',0); insert into a values(2,'a2',2); insert into a values(3,'a3',3); insert into a values(8,'a8',4); Create table B (c1 NUMBER(10),c3 VARCHAR(10)); insert into b values(1,'b1'); insert into b values(2,'b2'); insert into b values(3,'b3'); insert into b values(10,'b10'); Commit;
## 表自己对自己更新 示例4 UPDATE a d SET (d.c1) = (SELECT SUM(c.c4)