1. 程式人生 > 資料庫 >比較sqlserver不同資料庫之間的表結構差異

比較sqlserver不同資料庫之間的表結構差異

/*
使用說明:Old資料庫為DB_V1,New資料庫為[localhost].DB_V2。根據實際需要批量替換資料庫名稱
指令碼來源:
*/

-- 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