create trigger trg_delete
on A
for delete
as
    delete B from B,deleted where B.Aid=deleted.BaseID
go

解决方案 »

  1.   

    create function f_tb(@Aid int)
    returns @tb table(Aid int)
    as
    begin
          insert @tb select Aid from A where Aid=@Aid
          while @@rowcount>0
          begin
                insert @tb
                select A.Aid
                from A
                join @tb B on A.BaseID=B.Aid
                where not exists(select 1 from @tb where Aid=A.Aid)
          end      return
    end
    go--删除 
    declare @Aid int   --要删除的Aid
    set @Aid=1delete from A where Aid in(select Aid from f_tb(@Aid))
    delete from B where Aid in(select Aid from f_tb(@Aid))
      

  2.   

    create table A
    (
      Aid int,
      name varchar(10),
      BaseID int           
    )
    create table B
    (
      Bid int,
      name varchar(10),
      AID int           
    )
    insert A
    select 1,'张三',0 union
    select 2,'李较',1 union
    select 3,'王孙',2
    insert B
    select 1,'李城隍',3 union
    select 2,'黄莺',1
    go--测试 
    create function f_tb(@Aid int)
    returns @tb table(Aid int)
    as
    begin
          insert @tb select Aid from A where Aid=@Aid
          while @@rowcount>0
          begin
                insert @tb
                select A.Aid
                from A
                join @tb B on A.BaseID=B.Aid
                where not exists(select 1 from @tb where Aid=A.Aid)
          end      return
    end
    go--删除 
    declare @Aid int   --要删除的Aid
    set @Aid=1delete from B where Aid in(select Aid from f_tb(@Aid))
    delete from A where Aid in(select Aid from f_tb(@Aid))--查看
    select * from A
    select * from B--删除测试环境
    drop function f_tb
    drop table A,B
     
    --结果
    /*
    Aid         name       BaseID      
    ----------- ---------- ----------- (所影响的行数为 0 行)Bid         name       AID         
    ----------- ---------- ----------- (所影响的行数为 0 行)
    */
      

  3.   

    --创建用户定义函数,用于取得某个节点下所有子节点
    create function f_getchild(@AID int)
    returns @t table(AID INT,BaseID INT,Level INT)
    as
    begin
        declare @i int 
        set @i = 1
        
        insert into @t select Aid,BaseID,@i from A where AID=@AID
        
        while @@rowcount <> 0
        begin
            set @i = @i + 1
            
            insert into @t 
            select 
                A.Aid,A.BaseID,@i 
            from 
                A,@t t 
            where 
                A.Aid=t.BaseID and t.Level=@i-1
        end
        return
    end
    go--创建存储过程
    create procedure sp_deldata(@AID int)
    as
    begin   
        delete B from B,dbo.f_getchild(@AID) t where B.Aid = t.AID
        delete A from A,dbo.f_getchild(@AID) t where A.Aid = t.AID
    end
    go