[dba-SQLServer] Reference table in different db

jwcolby jwcolby at colbyconsulting.com
Thu Apr 1 08:02:18 CDT 2010


Guys,

I am building dynamic SQL in a stored procedure.  I pass in the name of the database, table etc.

This is what I currently do:

	Declare FieldCursor CURSOR FAST_FORWARD FOR
	SELECT * FROM tblCriteriaFieldData
	WHERE maxlength is not Null

This is what I need to do:

	Declare FieldCursor CURSOR FAST_FORWARD FOR
	SELECT * FROM @SomeDb.tblCriteriaFieldData
	WHERE maxlength is not Null

Where @SomeDB is a passed in database name.  Obviously this syntax is not correct.

I tried to declare an @SQL statement and then build up the select into that @SQL and then use:

	Declare FieldCursor CURSOR FAST_FORWARD FOR
	@SQL

but that doesn't work either.

So I need to know how to open a cursor for a table in another database where the database name is 
not hard coded.

Any assistance is greatly appreciated.

-- 
John W. Colby
www.ColbyConsulting.com



More information about the dba-SQLServer mailing list