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.
<pre>CREATE PROCEDURE MyProcedure
@DBName sysname
AS
DECLARE @cmd nvarchar(2000)
SET @cmd = N’SELECT * FROM ‘ + @DBName + ‘.dbo.SomeTable’
exec (@cmd)
GO</pre>
You can add more input parameters as needed.
Discuss This Question: 3  Replies
Jaimie El Rohi Nelaturi.