在 SqlServer 2000 上执行下列语句出错
drop table student cascade
请问在 SqlServer 2000上实现级联删除该怎么写呢?

解决方案 »

  1.   

    /*
    标题:两表通过字段关联进行级联删除。
    作者:爱新觉罗·毓华(十八年风雨,守得冰山雪莲花开) 
    时间:2008-11-20
    地点:广东深圳
    */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
      

  2.   

    SQL Server 不支持 drop table ... cascade 语句,用户需要自己手动删除那些引用删除表的表。不过可以通过 sysforeignkeys 系统表和动态语句实现。create procedure drop_cascade @tabname varchar(256)
    as
    declare @level int;
    set @level=0;declare @temp table (oid int,lvl int);
    insert into @temp values(object_id(@tabname),@level);
    while @@rowcount>0
    begin
     set @level=@level+1;
     insert into @temp
      select fkeyid,@level from sysforeignkeys 
      where rkeyid in (select oid from @temp where lvl=@level-1);
    enddeclare @sql varchar(8000);
    set @sql='';
    select @sql=@sql+','+quotename(object_schema_name(oid))+'.'+quotename(object_name(oid))
    from (select distinct oid,lvl from @temp t 
    where lvl=(select min(lvl) from @temp where oid=t.oid)) t
    order by lvl desc;
    set @sql='drop table '+stuff(@sql,1,1,'')+';';select @sql;
    goexec drop_cascade 'dbo.students';
      

  3.   

    简单点说,这句drop table student cascade改成什么,可实现删除?