在一台服务器上有a,b 两个数据库,结构相同,数据不同且有很多重复!
问题一:将a上的表aa 上的数据复制到b上的表aa上,要求不重复
问题二:将a上的多个表的数据复制到b上的相同表名的表上,要求不重复
问题三:批量删除将a上的表aa 上的列ccc的全部数据
大侠,我很菜,尽量详细点

解决方案 »

  1.   

    假设表的主键为均为ID,数据库a为dbA,数据库b为dbB:1.
    insert into dbB.dbo.aa
    select t.* from dbA.dbo.aa as t LEFT JOIN dbB.dbo.aa as b
    on a.ID = b.ID where b.ID IS NULL2.
    ----使用游标复制表中的数据到新库同名表中
    declare @TableName sysname,@sql varchar(1000)
    --创建游标,获得a库所有用户表
    declare cur CURSOR static for 
    select name from dbA.dbo.sysobjects where xtype = 'U' and status > 0
    --打开游标
    open cur
    --定位到游标第一行,并将表名称读出到变量@TableName中
    fetch next from cur into @TableName
    --如果定位成功则遍历所有用户表
    while @@fetch_status = 0
    begin
        --构建用于不重复插入的SQL字符串
        set @sql = '
        insert into dbB.dbo.' + @TableName + '
        select t.* from dbA.dbo.' + @TableName + ' as t 
        LEFT JOIN dbB.dbo.'@TableName + ' as b
        on a.ID = b.ID where b.ID IS NULL'
        --执行插入
        EXEC(@sql)
        --游标向下移动一行
        fetch next from cur into @TableName
    end
    --关闭游标
    close cur
    --清除游标占用的资源
    deallocate cur3.
    update dbA.dbo.aa set ccc = NULL