sql server新舊數據庫的表結構差異


問題:
工作過程中,不管是什么項目,伴隨着項目不斷升級版本,對應的項目數據庫業務版本也不斷升級,數據庫出現新增表、修改表、刪除表、新增字段、修改字段、刪除字段等變化,如果人工檢查,數據庫表和字段比較多的話,工作量就非常大。

解決方案:
這里博主為大家分享一個在工作過程中編寫的自動檢查數據庫表結構版本差異的通用腳本,只需要把新舊數據庫名稱批量替換成實際的名稱就可以,支持通過鏈接服務器跨服務器檢查不同服務器的兩個數據庫表結構差異。

腳本:

復制代碼
/*
    使用說明: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:

示例新數據庫DB_V2:

腳本運行結果:

結論:
從上面幾個圖可以看到,表和字段的差異部分就被自動檢測到了。

【轉載請注明博文來源:https://www.cnblogs.com/zhang502219048/p/11028767.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM