Oracle 2張表關聯更新表資訊的四個SQL

2021-08-31 17:00:59 字數 2364 閱讀 2043

oracle資料庫中2張表t_1和表t_2,t_1資訊需要根據t_2表資訊進行批量變更,2張表根據id進行關聯。

[b]1.建立2張表,沒有設定主鍵[/b]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)

);[b]2.為t_1表、t_2表插入資料[/b]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;

[i][b]3.刪除表資料[/b][/i]delete from t_1;

delete from t_2;

commit;

[b]4.希望用t_2表的資料更新t_1表的資料,前提是2個表的id[/b]

[b][color=red]方法一:[/color][/b]

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

[b][color=red]方法二:where條件使用exists[/color][/b]

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;

執行結果:

同方法一。

[b][color=red]方法三:游標[/color][/b]

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;

執行結果:

執行結果:同方法一。

[b][color=red]方法四:[/color][/b]

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);

Oracle 2張表關聯更新表資訊的四個SQL

本文出自 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 c...

oracle關聯表更新

如果有a表和b表,sql server中用 update a set field2 b.filed2 from a,b where a.field1 b.field1搞定,所以用慣了sql server的更新表語句,再用oracle的那真是特別的拗口。情景一 如果只是更新固定值,oracle和sql...

Oracle的關聯表更新(二)

oracle資料庫中有乙個表formtable main 159 dt1結構如下 mainid,id 161,100,161,101,161,102,162,103 162,104 163,105 現在增加乙個字段序號,實現如下的效果 mainid,id,xuhao 161,100,1 161,10...