通常來講,如何檢測兩張表的內容是否一致,體如今複製的時候發佈端和訂閱端的兩端的數據上面 數據庫
我這裏羅列了一些如何從數據庫層面來解決此類問題的方法 ide
第一步固然就是檢查記錄數是否一致,不然不用想其餘方法了~
這裏咱們用兩張表t1_old,t1_new來演示 工具
方法介紹 spa
方法一:老老實實看錶結構和表記錄數,弊端是根本看不到兩張表的數據是否一致,只是看到表結構和記錄數是否一致 code
--表結構: CREATE TABLE t1_old ( id int NOT NULL, log_time DATETIME DEFAULT '') ; CREATE TABLE t1_new ( id int NOT NULL, log_time DATETIME DEFAULT '') ;--兩表的記錄數都爲100條。select count(*) from t1_old;select count(*) from t1_new;
方法二:加法去重 union 運算符排除重複的,可是有bug,在某些情形下不能簡單表示結果集一致,至關於無效 orm
因爲Union 自己具有把上下兩條鏈接的記錄作惟一性排序,因此這樣檢測起來比較簡單 排序
SELECT COUNT(*)FROM ( SELECT * FROM [t1_old] UNION SELECT * FROM [t1_new] ) AS T;INSERT INTO [dbo].[t1_new] ( [id],[log_time] )VALUES(1,''),(3,''),(4,'')INSERT INTO [dbo].[t1_old] ( [id],[log_time] )VALUES(1,''),(2,''),(3,'')SELECT * FROM [dbo].[t1_new]SELECT * FROM [dbo].[t1_old]SELECT COUNT(*)FROM ( SELECT * FROM [t1_new] UNION SELECT * FROM [t1_old] ) AS T;
兩表數據 io
查詢出來的結果是4 table
方法三:EXCEPT 減法歸零 select
SELECT COUNT(*)FROM ( SELECT * FROM [dbo].[t1_new] EXCEPT SELECT * FROM [dbo].[t1_old] ) AS T;SELECT COUNT(*)FROM ( SELECT * FROM [dbo].[t1_old] EXCEPT SELECT * FROM [dbo].[t1_new] ) AS T;SELECT * FROM [dbo].[t1_new]SELECT * FROM [dbo].[t1_old]
這裏檢測出來結果不對,那麼就直接給出不一致的結論
方法四:用全表INNER JOIN,這個也是最爛的作法,固然這裏指的是在表記錄數超級多的狀況下
DECLARE @t1_newcount BIGINTDECLARE @count BIGINTSELECT @t1_newcount = COUNT(*)FROM t1_new;SELECT @count = COUNT(*)FROM [t1_old] AS a INNER JOIN [t1_new] AS b ON [b].[id] = [a].[id] AND [b].[log_time] = [a].[log_time] --若是表中還有其餘字段的自行添加PRINT @countPRINT @t1_newcountIF ( @count = @t1_newcount ) BEGIN SELECT 'equal' END ELSE BEGIN SELECT 'not equal' END
方法五:藉助SQLSERVER自帶的tablediff工具,當初微軟製做這個工具的目的就是用於比較複製中發佈表和訂閱表的數據一致
identical是相等的意思
方法六:藉助發佈端的驗證訂閱功能,驗證訂閱端跟發佈端的數據是否一致
方法七:用checksum校驗,比較兩張表裏的內容的checksum值是否一致
可是這種方法也只侷限於兩表結構一摸同樣
我把[t1_new]表的數據複製到一張新的表以便進行比較
SELECT * FROM [dbo].[t1_new]SELECT * FROM [dbo].[t1_newreplica]SELECT SUM(CHECKSUM(*)) AS checksumvalue FROM [dbo].[t1_old]SELECT SUM(CHECKSUM(*)) AS checksumvalue FROM [dbo].[t1_new]SELECT SUM(CHECKSUM(*)) AS checksumvalue FROM [dbo].[t1_newreplica]
總結
從上面幾種數據庫提供的方法來看,用EXCEPT減法來歸零相對來講比較可靠,其餘的方法比較適合在特定的情形下來檢測