Monday, March 19, 2012

Make Dynamic cursor

I want to a create cursor, data get in this cursor is got from a table which i don't know name (the name table can change). But i can't do the select to create this cursor by exec. Please help me, thanks.Originally posted by patexyz
I want to a create cursor, data get in this cursor is got from a table which i don't know name (the name table can change). But i can't do the select to create this cursor by exec. Please help me, thanks.

Try this:

use pubs
go

declare @.Table as Varchar(128)
set @.Table = 'Authors'

declare @.SQL Varchar(1000)

set @.SQL = ''

set @.SQL = @.SQL + ' declare DYNCUR cursor for select * from ' + @.Table
set @.SQL = @.SQL + ' open DYNCUR'
set @.SQL = @.SQL + ' fetch next from DYNCUR'
set @.SQL = @.SQL + ' while @.@.fetch_status = 0'
set @.SQL = @.SQL + ' begin'
set @.SQL = @.SQL + ' fetch next from DYNCUR'
set @.SQL = @.SQL + ' end'
set @.SQL = @.SQL + ' close DYNCUR'
set @.SQL = @.SQL + ' deallocate DYNCUR'

exec(@.SQL)

No comments:

Post a Comment