2 Datenbanken vergleichen
Wie im Artikel Prüfen ob Inhalt 2er Tabellen gleich ist beschrieben, kann es nützlich sein, zu überprüfen ob die Inhalte von Tabellen in 2 Datenbanken identisch sind. Folgendes Script erledigt dies auf einem MS SQL Server komplett automatisch:
if exists (select 1
from sysobjects
where id = object_id('COMP_RES ')
and type = 'U')
drop table COMP_RES
go
CREATE TABLE COMP_RES (
TABLE_NAME varchar(200),
DIFFERENCES int,
SQL varchar(8000),
LC datetime not null default getDate()
)
go
set nocount on
declare @table varchar(200)
declare @col varchar(8000)
declare @col_tmp varchar(200)
declare @db_1 varchar(250)
declare @db_2 varchar(250)
declare @schema varchar(100)
declare @sql varchar(8000)
exec ('truncate table COMP_RES')
set @schema = '<SCHEMA_TO COMPARE>'
set @db_1 = ''
set @db_2 = ''
declare tables cursor for
select TABLE_SCHEMA + '.' + TABLE_NAME from information_schema.tables where table_type='base table' and table_schema=@schema order by table_name
open tables
fetch next from tables into @table
while @@fetch_status = 0
begin
if not @table like '%COMP_RES'
begin
set @col=''
declare columns cursor for
select column_name from information_schema.columns where table_schema+'.'+table_name=@table
open columns
fetch next from columns into @col_tmp
while @@fetch_status = 0
begin
if @col <> ''
set @col = @col + ', '
set @col = @col + @col_tmp
fetch next from columns into @col_tmp
end
CLOSE columns
DEALLOCATE columns
set @sql = 'SELECT COUNT(*) AS DIFFERENCES FROM ( (SELECT ' + @col + ', count(*) AS COUNT FROM ' + @db_1+'.'+@table + ' GROUP BY ' + @col + ' EXCEPT ' + 'SELECT ' + @col + ', count(*) AS COUNT FROM ' + @db_2+'.'+@table + ' GROUP BY ' + @col + ' )' + 'UNION ALL' + '(SELECT ' + @col + ', count(*) AS COUNT FROM ' + @db_2+'.'+@table + ' GROUP BY ' + @col + ' EXCEPT ' + 'SELECT ' + @col + ', count(*) AS COUNT FROM ' + @db_1+'.'+@table + ' GROUP BY ' + @col + ' ) )T'
--print @sql
exec ('INSERT INTO COMP_RES (TABLE_NAME, DIFFERENCES, SQL) VALUES ('''+@table+''', null, '''+@sql+''')')
exec ('UPDATE COMP_RES SET DIFFERENCES = ('+@sql+'), LC=getDate() WHERE TABLE_NAME='''+@table+'''')
end
fetch next from tables into @table
end
CLOSE tables
DEALLOCATE tables
Zunächst wird im Standardschema des verwendeten Benutzers eine Tabelle "COMP_RES" angelegt, in der die Ergebnisse des Vergleichs abgelegt werden. Anschließend werden alle Tabellen in @db_1 gesucht und die aus dem oben erwähnten Artikel bekannten Vergleich SQL's gebaut. Diese werden anschließend ausgeführt und die Ergebnisse in der Tabelle COMP_RES abgelegt. So lässt sich die Aufgabe die Datenbanken zu vergleichen wunderbar auf verschiedene Datenbanken anwenden und/oder automatisieren.