SQL – compare number of records in each tables of different database at remote server

Some time during development you need to compare tables(same tables) of different different database , and things becomes tough if both database are on remote server.

At such time you need to query to separate database of remote server.

Using ‘Linked server’ you can query remote database.

To establish linked server, first you have to create two linked server in order to access them, you can add it using following command:

exec sp_addlinkedserver @server=[server1]
exec sp_addlinkedserver @server=[server2]

(Assuming you are connected with same database locally,  and you have to also give authentication information in case of any there)

Then by running ‘cursor’ on all tables you can achieve result.

declare tmpCUR cursor for

select name from sysobjects where xtype=’U’

/*   to scan each tables in database   */

open tmpCUR

declare @tmpName nvarchar(400)

fetch next from tmpCUR into @tmpName While @@fetch_Status = 0
BEGIN

declare @query nvarchar(1000)

set @query=’select ”’ + @tmpName+”’,count(*) from [server1].[database1].dbo.’ + @tmpName
exec sp_executesql @query

set @query=’select ”’ + @tmpName+”’,count(*) from [server2].[database2].dbo.’ +@tmpName
exec sp_executesql @query

fetch next from tmpCUR
into @tmpName

END

CLOSE tmpCUR
DEALLOCATE tmpCUR

Advertisements