問題:
工做過程當中,無論是什麼項目,伴隨着項目不斷升級版本,對應的項目數據庫業務版本也不斷升級,數據庫出現新增表、修改表、刪除表、新增字段、修改字段、刪除字段等變化,若是人工檢查,數據庫表和字段比較多的話,工做量就很是大。html
解決方案:
這裏博主爲你們分享一個在工做過程當中編寫的自動檢查數據庫表結構版本差別的通用腳本,只須要把新舊數據庫名稱批量替換成實際的名稱就能夠,支持經過連接服務器跨服務器檢查不一樣服務器的兩個數據庫表結構差別。數據庫
腳本:
服務器
/* 使用說明: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
示例舊數據庫DB_V1:
spa
示例新數據庫DB_V2:
3d
腳本運行結果:
code
結論:
從上面幾個圖能夠看到,表和字段的差別部分就被自動檢測到了。htm
【轉載請註明博文來源:http://www.javashuo.com/article/p-srvopkce-eh.html】blog