Wednesday, July 18, 2012

Count Difference of Tables in Two Databases


SET NOCOUNT ON;
DECLARE @name VARCHAR(50)
DECLARE @DBName1 VARCHAR(50)
DECLARE @DBName2 VARCHAR(50)
DECLARE @QName1 VARCHAR(250)
DECLARE @QName2 VARCHAR(MAX)
Create Table #temp(Dbname varchar(50),tablename varchar(50), Count1 int, Count2 varchar(50))
SET @DBName1= 'DataBase Name 1'
SET @QName1= @DBName1 +'.sys.tables'
SET @QName2 ='Insert into #temp(Dbname,tablename) '+  'Select ' +'''' +@DBName1+''', name from '+  @QName1 + ' order by 1'
--PRINT @QName2
EXEC (@QName2)

Create Table #temp1(Dbname varchar(50),tablename varchar(50))
SET @DBName2='DataBase Name 2'
SET @QName1= @DBName2 +'.sys.tables'
SET @QName2 ='Insert into #temp1(Dbname,tablename) '+  'Select ' +'''' +@DBName2+''', name from '+  @QName1 + ' order by 1'
--PRINT @QName2
EXEC (@QName2)

UPDATE #temp
SET Count2 = 'Not present'
Where tablename IN(Select A.tablename FROM #temp A LEFT OUTER JOIN #temp1 B
ON A.tablename = B.tablename WHERE B.tablename is null)

DECLARE db_cursor CURSOR FOR 
  Select tablename from #temp
OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0 
BEGIN 
      SET @QName1 = 'Update  #temp SET Count1 =( Select COUNT(*) FROM ' +@DBName1+'.dbo.' + @name +
                     ') where Tablename= '''+@name +''''
      --PRINT @QName1
      SET @QName2 = 'IF EXISTS (SELECT name FROM ' +@DBName2 +'.sys.tables where name='''+ @name +
                    ''')Update  #temp SET Count2 =(Select COUNT(*) FROM ' +@DBName2+'.dbo.' + @name +
                     ') where Tablename= '''+@name +''''
      --PRINT @QName2
      EXEC (@QName1)
      EXEC (@QName2)
      FETCH NEXT FROM db_cursor INTO @name 
END 
Select tablename,Count1 As CountInSourceTable, Count2 AS CountInDestTable from #temp order by 1
CLOSE db_cursor 
DEALLOCATE db_cursor
Drop TABLE #temp
Drop TABLE #temp1
SET NOCOUNT OFF;

No comments:

Post a Comment