Here's my dilema. I'm trying to create a SQL script that will report back
to me every table that has a different row count from one database to
another. I believe the best way to accomplish this is using a CURSOR to
fetch through the tables in the DB and print those where the record count
differs. Here is what I'm trying to do:
DECLARE @.Table nvarchar(40)
DECLARE Table_CURSOR CURSOR FOR
select sysobjects.name
from sysobjects, syscolumns, systypes
where syscolumns.id = sysobjects.id and syscolumns.xtype
= systypes.xtype
and sysobjects.xtype = 'U'
group by sysobjects.name
order by sysobjects.name
OPEN Table_CURSOR
FETCH NEXT FROM Table_CURSOR
INTO @.Table
WHILE @.@.FETCH_STATUS = 0
BEGIN
IF (SELECT COUNT(*) FROM Database1..[@.Table] WHERE ID NOT IN (SELECT ID
FROM Database2..[@.Table])) > 1
BEGIN
Print @.Table
END
FETCH NEXT FROM Table_CURSOR
INTO @.Table
END
CLOSE Table_CURSOR
DEALLOCATE Table_CURSOR
However, I get errors on "Invalid object name 'Database1..@.Table' and
"Invalid object name 'Database2..@.Table'.
I've tried without the bracket signs around [@.Table] as well, but then get
an error "Incorrect Syntax near '@.Table'.
Any ideas? Is there an easier way to achieve this? Thanks in advance,
JasonThe problem is that you cannot substitute variables for object names (like
databases or tables). However, you can execute dynamic sql. Here is a good
article. Also, useful is the undocumented sp_msforeachtable procedure.
http://www.databasejournal.com/feat...cle.php/1438931
"Jason" <jason@.nospam.com> wrote in message
news:OTGTuNX5FHA.2036@.TK2MSFTNGP14.phx.gbl...
> Here's my dilema. I'm trying to create a SQL script that will report back
> to me every table that has a different row count from one database to
> another. I believe the best way to accomplish this is using a CURSOR to
> fetch through the tables in the DB and print those where the record count
> differs. Here is what I'm trying to do:
> DECLARE @.Table nvarchar(40)
> DECLARE Table_CURSOR CURSOR FOR
> select sysobjects.name
> from sysobjects, syscolumns, systypes
> where syscolumns.id = sysobjects.id and syscolumns.xtype
> = systypes.xtype
> and sysobjects.xtype = 'U'
> group by sysobjects.name
> order by sysobjects.name
> OPEN Table_CURSOR
> FETCH NEXT FROM Table_CURSOR
> INTO @.Table
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> IF (SELECT COUNT(*) FROM Database1..[@.Table] WHERE ID NOT IN (SELECT ID
> FROM Database2..[@.Table])) > 1
> BEGIN
> Print @.Table
> END
> FETCH NEXT FROM Table_CURSOR
> INTO @.Table
> END
> CLOSE Table_CURSOR
> DEALLOCATE Table_CURSOR
> However, I get errors on "Invalid object name 'Database1..@.Table' and
> "Invalid object name 'Database2..@.Table'.
> I've tried without the bracket signs around [@.Table] as well, but then get
> an error "Incorrect Syntax near '@.Table'.
> Any ideas? Is there an easier way to achieve this? Thanks in advance,
> Jason
>
Subscribe to:
Post Comments (Atom)
 
No comments:
Post a Comment