Question

  Asked: Mar 11 2008   10:13 PM GMT
  Asked by: SQL Server Ask the Experts


Passing a database name as a stored procedure parameter


Stored procedures, T-SQL

I would like to be able to pass the name of a database as a parameter to a stored procedure. This db would be used for certain queries and may be different from the db where the stored procedure runs. Is it possible to specify a database name from within the T-SQL of the stored procedure? If so, how?

Subscribe to Alerts! Get questions and answers delivered to your Inbox.


E-mail me updates on this question



   SUBSCRIBE

hidden modal window

Answer Wiki (Improve, edit or add to this answer)


 RATE THIS ANSWER
0
Click to Vote:
  •   0
  •  0



Yes you can do this, however it is not recommended. You have to use a technique called dynamic SQL. There are security risks on using dynamic SQL as the user who runs the procedure much have access to the table or tables listed in the dynamic SQL, and dynamic SQL is subject to a SQL injection attack.

That said, the syntax would be something like this.

CREATE PROCEDURE MyProcedure
@DBName sysname
AS
DECLARE @cmd nvarchar(2000)
SET @cmd = N'SELECT * FROM ' + @DBName + '.dbo.SomeTable'
exec (@cmd)
GO


You can add more input parameters as needed.
  • AddThis Social Bookmark Button

Browse more Questions and Answers on Database and SQL Server.

Looking for relevant Database Whitepapers? Visit the SearchOracle.com Research Library.


Discuss This Answer


You must be logged-in to discuss a question. Log-in/Register

Mrdenny  |   Mar 12 2008  6:51AM GMT

Check out my SQL Server blog “SQL Server with Mr Denny” for more SQL Server information.