您的位置:首页 > 数据库 > Oracle

Oracle 2张表关联更新表信息的四个SQL

2013-07-17 08:49 344 查看
本文出自“mymailzxj”

Oracle数据库中2张表T_1和表T_2,T_1信息需要根据T_2表信息进行批量变更,2张表根据ID进行关联。

1.创建2张表,没有设置主键create table T_1

(

ID NUMBER(2),

YEAR VARCHAR2(20),

MONTH VARCHAR2(10)

);

create table T_2

(

ID NUMBER(2),

YEAR VARCHAR2(20),

MONTH VARCHAR2(10)

);

2.为T_1表、T_2表插入数据insert into T_1 (ID, YEAR, MONTH)values (1, '2011', '1');

insert into T_1 (ID, YEAR, MONTH)values (2, '2011', '2');

insert into T_1 (ID, YEAR, MONTH)values (3, '2011', '3');

commit;

insert into T_2 (ID, YEAR, MONTH)values (1, '2010', '11');

insert into T_2 (ID, YEAR, MONTH)values (2, '2010', '12');

commit;

3.删除表数据delete from T_1;

delete from t_2;

commit;

4.希望用t_2表的数据更新t_1表的数据,前提是2个表的id

方法一:

update t_1 a set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id);

commit;

执行结果结果:

1 2010 11

2 2010 12

3

执行结果会将t_1.id =3的year,month置为空,因为这个语句是对t_1表记录进行全量变更,如果在T_2表中不存在记录则会对T_1表记录置空;

处理方法:如果不想得到这样的结果,需要增加一个where条件。

update t_1 a set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id)

where a.id=(select c.id from year4 c where a.id=c.id);

commit;

执行结果:

1 2010 11

2 2010 12

3 2011 3

方法二:where条件使用exists

update t_1 a set (a.year,a.month) =(select b.year,b.month from T_2 b where b.id=a.id)

where exists (select 1 from T_2 b where b.id=a.id)

commit;

执行结果:

同方法一。

方法三:游标

declare

cursor target_cur is select year,month,id from t_2;

begin

for my_cur in target_cur loop

update t_1 set year=my_cur.year,month=my_cur.month

where id=my_cur.id;

end loop;

end;

执行结果:

执行结果:同方法一。

方法四:

update (select a.year aYear,a.id aId,a.month aMonth,b.year bYear,b.id bId,b.month bMonth from t_1 a,t_2 b where a.id = b.id) set aYear = bYear,aMonth = bMonth;

commit;

执行结果:

报oracle错误ora-01779,无法修改于非键值保存表对应列。

处理方法:将2个表的id设置为各自表的主键,然后再次执行后得到正确结果。

alter table T_1 add constraint t1_key_id primary key (ID);

alter table T_2 add constraint t2_key_id primary key (ID);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: