2016-04-30 48 views
1
之間複製數據

我有兩個數據庫,數據庫A和數據庫B,這是相同的,除了在數據庫B的一些表的約幾個新列需要幫助兩個類似的數據庫表

兩個數據庫包含相同數量的表(1160個表)中,我在數據庫B中添加了約40個表中的新增列,這是唯一使其與數據庫A不同的因素。

我清空了數據庫B中的所有表並希望插入數據庫A到數據庫B的每個表中的所有數據,僅留下具有與源數據庫A不同的列數的40個表格。

我需要幫助腳本循環遍歷數據庫A中的所有表,檢查列是否相同,然後將其內容複製到數據庫B中的表中,如果列不相同,則應該留下錯誤的表名。

請幫忙。

+0

那麼你的問題到底是什麼? –

+0

我試過了:「Select * into DatabaseB.dbo.table1 From DatabaseA.dbo.table1 .... That works,but I need a script that can loop through all table and copy the database of each table of Database A into數據庫B中的每個對應表 – DoreenSly

+0

@DoreenSly,你還在等待答案嗎?你是否有DBO模式中的表?你有沒有標識字段? – FLICKER

回答

1

這應該工作,假設你所有的表都是DBO。 萬一你有身份證,請看我的評論

-- select only tables that have the same number of columns 
declare tbls cursor for with tblsA as (
select t.name, count(*) as colCount 
from DatabaseA.sys.tables t 
    inner join DatabaseA.sys.columns c on c.object_id = t.object_id 
group by t.name 
) 
, tblsB as (
select t.name, count(*) as colCount 
from DatabaseB.sys.tables t 
    inner join DatabaseB.sys.columns c on c.object_id = t.object_id 
group by t.name 
) 
select tblsA.name as TableName 
from tblsA 
    inner join tblsB on tblsB.name = tblsA.name and tblsB.colCount = tblsA.colCount 


declare @tblName varchar(100) 
declare @sqlText nvarchar(max) 
open tbls 
fetch next from tbls into @tblName 
while @@FETCH_STATUS = 0 
begin 
    print 'Inserting into ' + @tblName 

    --un-comment if you don't have identity fields. 
    --you will need more code here if some table have identity field and some don't 
    --set @sqlText = 'SET IDENTITY_INSERT DatabaseB..' + @tblName + ' ON' 
    --exec(@sqlText) 

    set @sqlText = 'insert into DatabaseB..' + @tblName + ' select * from DatabaseA..' + @tblName 
    exec(@sqlText) 

    fetch next from tbls into @tblName 
end 

close tbls 
deallocate tbls 
+0

@閃爍......感謝數十億次......完美地工作我希望它移動了同列的表的數據,並跳過了不相等的數據.....我使用相同的代碼來獲得少數不相等的表的列表,並且我將一個接一個地移動它們自己的數據。 – DoreenSly