比较sqlserver不同数据库之间的表结构差异

/*
使用说明:Old数据库为DB_V1,New数据库为[localhost].DB_V2。根据实际需要批量替换数据库名称
脚本来源:https://www.cnblogs.com/zhang502219048/p/11028767.html
*/

-- sysobjects插入临时表
select s.name + '.' + t.name as TableName, t.* into #tempTA
from DB_V1.sys.tables t
inner join DB_V1.sys.schemas s on s.schema_id = t.schema_id

select s.name + '.' + t.name as TableName, t.* into #tempTB
from [localhost].DB_V2.sys.tables t
inner join [localhost].DB_V2.sys.schemas s on s.schema_id = t.schema_id

-- syscolumns插入临时表
select * into #tempCA from DB_V1.dbo.syscolumns
select * into #tempCB from [localhost].DB_V2.dbo.syscolumns

-- 第一个数据库表和字段
select b.TableName as 表名, a.name as 字段名, a.length as 长度, c.name as 类型
into #tempA
from #tempCA a
inner join #tempTA b on b.object_id = a.id
inner join systypes c on c.xusertype = a.xusertype
order by b.name
-- 第二个数据库表和字段
select b.TableName as 表名, a.name as 字段名, a.length as 长度, c.name as 类型
into #tempB
from #tempCB a
inner join #tempTB b on b.object_id = a.id
inner join systypes c on c.xusertype = a.xusertype
order by b.name

--删掉的字段
select * from
(
select * from #tempA
except
select * from #tempB
) a;

--增加的字段
select * from
(
select * from #tempB
except
select * from #tempA
) a;

--select * from #tempA
--select * from #tempB

drop table #tempTA, #tempTB, #tempCA, #tempCB, #tempA, #tempB

posted on 2020-11-25 13:28  阿陶学长  阅读(449)  评论(0编辑  收藏  举报