Link to home
Start Free TrialLog in
Avatar of mecks12
mecks12

asked on

Database Context and referencing user tables

Is it possible to perform SQL statements referencing user tables from within a stored procedure by passing in the database as a parameter?

Context: I have multiple databases with the same table structures that require the same stored procedure executed against them.  I would like to be able to reference user tables for processing within these stored procedures.  I keep running up against "Invalid Object Name" errors.  

Example below created to run against Northwind database which creates the same error as I get in my real application.  The DB_Name() will display as 'Northwind' just prior to the SELECT * FROM customers. But the Invalid object name 'Customers' message comes right after this.  

Running a query against the system tables from within the Stored procedure brings back expected results.  I have tried to solve this using dynamic sql but keeping running into scope problems related to temp tables or cursors that are needed in the logic.



EXAMPLE:

CREATE PROCEDURE sp_DbQuery @database VARCHAR(20), @mode tinyint=0

AS
BEGIN

IF @mode = 0
BEGIN
   DECLARE @lvSQL varchar(4000)
   SET @lvSQL = 'EXEC ' + @database + '..sp_DbQuery ''' + @database + ''',1'

   PRINT 'DbQuery = ' + @lvSQL
   EXEC(@lvSQL)
END
ELSE
BEGIN
PRINT DB_NAME()
SELECT * FROM Customers INTO #TempCust
....Additional logic which uses temp tables and cursors

END

END
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mecks12
mecks12

ASKER

Marking it as a system object was what I was missing!  Thanks!