zoukankan      html  css  js  c++  java
  • 两表通过字段关联进行级联删除。

     
    create table ta(id int not null)
    create table tb(id int , aid int)
    insert into ta values(1)
    insert into ta values(2)
    insert into tb values(1 , 1)
    insert into tb values(2 , 2)
    insert into tb values(3 , 1)
    go
     
    --一、查看原始数据
    --ta表的原始数据
    select * from ta
    /*
    id          
    ----------- 
    1
    2
    */
    --tb表的原始数据
    select * from tb
    /*
    id          aid         
    ----------- ----------- 
    1           1
    2           2
    3           1
    */
     
    --二、看看没有创建级联删除时的情况(删除ta表id=1的数据,看看是否影响tb表)
    delete from ta where id = 1
    select * from ta
    /*
    id          
    ----------- 
    2
    */
    select * from tb
    /*
    id          aid         
    ----------- ----------- 
    1           1
    2           2
    3           1
    */
     
    --三、恢复原始数据,创建级联删除,删除ta表id=1的数据,看看是否影响tb表
    insert into ta values(1)
    --为ta创建主健
    alter table ta add constraint pk_ta_id primary key (id)
    go
    --为tb创建外健,并指定级联删除
    alter table tb add constraint fk_tb_aid foreign key (aid) references ta(id) on delete cascade
    go
    delete from ta where id = 1
    select * from ta
    /*
    id          
    ----------- 
    2
    */
    select * from tb
    /*
    id          aid         
    ----------- ----------- 
    2           2
    */
     
    --删除级联约束
    alter table tb drop constraint fk_tb_aid
    go
    --删除测试表
    drop table ta , tb
    go
  • 相关阅读:
    1-15-2-RAID1 企业级RAID磁盘阵列的搭建(RAID1、RAID5、RAID10)
    1-15-1 RAID磁盘阵列的原理和搭建
    伪随机数算法(一)
    Swing---WindowConstants
    cmd_ping命令
    开灯问题
    freopen()函数
    Beginning Python Chapter 3 Notes
    Beginning Python Chapter 2 Notes
    String | StringBuffer | StringBuilder 比较
  • 原文地址:https://www.cnblogs.com/smallyi/p/6515158.html
Copyright © 2011-2022 走看看