各位朋友一台数据库服务器有数据库A1 和数据库A2   他们都有一个通格式叫datas的表
现在想用SQL脚本实现两个功能
1、将A1的datas表的数据写到A2的datas表,如果存在向相同行自动跳过不覆盖(有一个唯一编号NUM列表,A2的NUM列没有唯一约束)
2、在A2上创建UPDATE触发条件,当datas表发生UPADTE行为时将更新后的数据同样更新到A1的datas表请各位指教!

解决方案 »

  1.   


    --插入
    insert into 数据库A1.dbo.datas
    select * from 数据库A2.dbo.datas m where 
    not exists ( select 1 from 数据库A1.dbo.datas where NUM = m.NUM)
    --触发器同理
      

  2.   

    使用触发器来实现、create trigger t1
    on tb
    for insert,update
    as
    begin
       insert into db2.dbo.tb
       from  inserted t
       where not exists(select 1 from db2.dbo.tb where id=t.id)
    end
      

  3.   

    如果不采用2F的触发器,可以尝试定义insert 和 update 。
    比如满足条件且数据存在则update,满足条件且数据不存在则insert。
    这种方式可以做成批处理或者定时agent作业,通常用在非实时性数据交换环境。
      

  4.   

    请问一下lz,假设在A2执行触发器更新A1时,如果更新的NUM列与A1的NUM相同了,这个触发器岂不是会报错吗
    因为A1上有唯一索引列NUM
      

  5.   

    create trigger tri_a1
    on db1.dbo.a1
    for insert,update
    as
    begin
       insert into db2.dbo.a2  
        select *  from  inserted a
       where not exists(select 1 from inserted where num=db2.dbo.a2.num)
    end
    create trigger tru_a2
    on db2.dbo.a2
    for update
    as
    begin
       update  into db1.dbo.a1
    set col1=  a.clo1,
    ....
         from  inserted a
       where  num=db1.dbo.a1.num
    end
      

  6.   

    2楼的代码提示错误,
    create trigger t1
    on t
    for insert,update
    as
    begin
       insert into db2.dbo.tb
       from  inserted t
       where not exists(select 1 from db2.dbo.tb where id=t.id)
    end服务器: 消息 156,级别 15,状态 1,过程 t1,行 7
    在关键字 'from' 附近有语法错误。
      

  7.   

    2楼的代码提示错误,
    create trigger t1
    on t
    for insert,update
    as
    begin
       insert into db2.dbo.tb
       from  inserted t
       where not exists(select 1 from db2.dbo.tb where id=t.id)
    end服务器: 消息 156,级别 15,状态 1,过程 t1,行 7
    在关键字 'from' 附近有语法错误。