常用sql----实现关联表的数据级联更新

本文介绍了如何在不知道具体关联关系的情况下,通过SQL查询找到主外键关联,并实现多个表的数据级联更新。首先,查询表间主外键关系,然后删除外键约束,接着创建临时表并更新主表与子表的主键ID,最后重建外键约束,完成级联更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近对多个表要进行级联更新主键id,但又不知道主外键关联关系,所以打了草稿

 

 

--搜索表间 的关系--主外键
SELECT   a.table_name,a.constraint_name,b.column_name,p.table_name
  from   user_constraints   a,   user_cons_columns   b ,user_constraints   p
  where   --a.table_name   =   'your_table '   and   
       a.constraint_type= 'R' 
      and   a.constraint_name=b.constraint_name
      and   a.r_constraint_name = p.constraint_name
      
--主外键     
 select table_name as 表名,constraint_name from user_constraints where constraint_type='R';


--删除外键
alter table bird  drop CONSTRAINT fk_cat_id;


--更新主表
create table tem_bird
as
select rownum as newid,id as old_id from bird;
update bird c 
set c.id=(select tm.newid from tem_bird tm where c.id=tm.old_id);


--创建子表临时表
create table tem_cat
as
select rownum as newid,id as old_id from cat;


--更新子表
update cat c 
set c.id=(select tm.newid from tem_cat tm where c.id=tm.old_id);


--更新主表
update bird c 
set c.catid=(select tm.newid from tem_cat tm where c.catid=tm.old_id);
commit;


--建立关联外键
alter table  bird add  CONSTRAINT fk_cat_id FOREIGN KEY (catid) REFERENCES cat (ID) ENABLE ;


drop table tem_cat;
drop table tem_bird;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值