现在有2个表A和B,A中有字段ProductID,Name,Re(ProductID为主键且自动增一)
                B中有字段ProductID,Name,Introduce
A中ProductID,Name 和B中的是一样的。
现在当我删除B的一列时,要把对应的A中的列同步删除掉,怎么操作?利用触发器,希望给个完全的触发器设计代码,谢谢!!在线等

解决方案 »

  1.   

    --> Test Data: [tableA]
    if object_id('[tableA]') is not null drop table [tableA]
    create table [tableA] ([ProductID] int,[Name] varchar(5),[Re] varchar(50))
    insert into [tableA]
    select 1,'name1','r1' union all
    select 2,'name2','r2' union all
    select 3,'name3','r3'
    --> Test Data: [tableB]
    if object_id('[tableB]') is not null drop table [tableB]
    create table [tableB] ([ProductID] int,[Name] varchar(5),[Introduce] varchar(50))
    insert into [tableB]
    select 1,'name1',null union all
    select 2,'name2',null--select * from [tableA]
    --select * from [tableB]
    go
    --Code
    create trigger tr_del on tableB for delete
    as
    begin
      delete from tableA where [ProductID]=(select [ProductID] from deleted) 
      and [Name]=(select [Name] from deleted) 
    end
    go
    delete from tableB where [ProductID]=1
    --delete from tableB where [ProductID]=2
    select * from [tableA]
    select * from [tableB]
    --Drop--Result
    /*
    (1 行受影响)
    ProductID   Name  Re
    ----------- ----- --------------------------------------------------
    2           name2 r2
    3           name3 r3(2 行受影响)ProductID   Name  Introduce
    ----------- ----- --------------------------------------------------
    2           name2 NULL
    */