我有两个数据库,数据库A和数据库B,除了数据库B中某些表中的几个新列外,它们是相同的。
这两个数据库包含相同数量的表(1160个表)。我在数据库B中向大约40个表添加了列。这是与数据库A唯一不同的东西。
我清空了数据库B中的所有表,并希望将数据库A的每个表中的所有数据插入数据库B,只留下40个表的列数与源数据库A不同。
我需要一个脚本来遍历数据库A中的所有表,检查列是否相同,然后将其内容复制到数据库B中的那个表。如果列不相同,则应该留下错误表名。
答案 0 :(得分: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