Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL stored procedure

Posted on 2011-09-28
5
Medium Priority
?
219 Views
Last Modified: 2012-08-13
Is there a way to make the name of the database used in a stored procedure a variable.  Can I have 1 stored procedure that runs in different databases based upon the name of the  database name I pass in as a parameter.  

"a USE database statement is not allowed in a procedure, function or trigger."  = error from SQL
0
Comment
Question by:dastaub
5 Comments
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36716806
select * from your_database_name..your_table_name
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 36716807
If you pass in the db name as a parameter, then you could try something like this in your code:

IF @db_name = 'db1' SELECT * FROM db1.dbo.MyTable
IF @db_name = 'db2' SELECT * FROM db2.dbo.MyTable
IF @db_name = 'db3' SELECT * FROM db3.dbo.MyTable
-- et cetera

Open in new window


If you do not want to specify the databases up front, you will have to use dynamic SQL.
0
 
LVL 25

Accepted Solution

by:
Lee Savidge earned 2000 total points
ID: 36716836
Yes, but the simplest thing to use is dynamic SQL.
create procedure myProc (@nvchDB nvarchar(100))
as
begin
    exec ('select * from ' + @nvchDB + '.dbo.myTable')
end
go

Open in new window

0
 

Author Comment

by:dastaub
ID: 36716988
exec ('use ' + @nvchDB )

i tried this, but it appears to be ignored by the stored procedure.  if this worked, I would only have to change 1 line of code
0
 
LVL 25

Expert Comment

by:Lee Savidge
ID: 36717457
You can't do that.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question