Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable in Cursor declaration

Status
Not open for further replies.

balor

Programmer
Jul 24, 2000
74
How do I use a variable in the FOR expression for a cursor.

I want to do something like this:

SET @sSQL = 'SELECT *
FROM ' + @sLinkedDBName + '...Table1'

DECLARE TheCursor CURSOR
FOR @sSQL

OPEN TheCursor
.
.
.


How do I use the "@sLinkedDBName" - variable in the FOR expression? It does not like when i first set it in a variable and then use that variable in the expression.

//Balor


 
Are you using a linked server? In any case have you tried using OPENQUERY()? JHall
 
You can't use variables in OPENQUERY() either.

I'm using 21 allmost identical linked Access databases. Right now I have the declaration of the cursor and the "FOR"-SQL code written 21 times. The code is identical except for the linked server name. I should want to use a variable for the server name instead.
 
I tried this and it works but you have to create global cursors

DECLARE @Server varchar(50)
DECLARE @SQLString varchar(2048)

SELECT @Server = 'Yourserver'
SELECT @SQLString = 'DECLARE TheCursor CURSOR GLOBAL FOR ' +
'SELECT yourfieldlist FROM OPENQUERY(' + @Server + ', ' + CHAR(39) + 'your select goes here' + CHAR(39) + ')'

EXEC(@SQLString)
OPEN TheCursor
do other stuff here
CLOSE TheCursor
DEALLOCATE TheCursor
JHall
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top