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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi ScottPletcher,
Please have a look at:
https://www.experts-exchange.com/questions/21414736/Shared-Stored-Procedures.html
Dabas
Dabas
Please have a look at:
https://www.experts-exchange.com/questions/21414736/Shared-Stored-Procedures.html
Dabas
Dabas
ASKER