How do I go through a cursor to perform logic on multiple tables? (The table names are in the cursor)
I get the feeling this is pretty basic database work, but it isn't for me. I'm trying to get a list of all of my tombstone tables from system tables and store the results in a cursor. I'm then trying to perform some logic on each of those tables I'm having trouble doing so.
Any help would be greatly appreciated.
Here is the error I get: Must declare the table variable "@tablename"
Here is the code:
declare tombstonetables cursor for
(select name from sys.objects
where
name like'%tombstone%'
and type = 'U'--for user_table
)
Print 'Begin purging tombstone tables'
declare @tablena开发者_如何学JAVAme varchar(250)
open tombstonetables
fetch next from tombstonetables into @tablename
WHILE @@FETCH_STATUS = 0
begin
select * from @tablename--real logic goes here later
fetch next from tombstonetables into @tablename
end
close tombstonetables
deallocate tombstonetables
Looks like you need to use Dynamic SQL
Here is a reference to a simple walk through http://www.mssqltips.com/tip.asp?tip=1160
You will probably need to make use of sp_executesql
Here is a simple example of using Dynamic SQL with your example
DECLARE @DynamicSQL nvarchar(100)
WHILE @@FETCH_STATUS = 0
begin
SET @DynamicSQL = 'select * from ' + @tablename --real logic goes here later
EXEC @DynamicSQL
fetch next from tombstonetables into @tablename
end
精彩评论