Solved

SQL stored procedure

Posted on 2011-09-28
5
213 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 92

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 500 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

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
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.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

837 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