USE DATABASE

0 pts.
Tags:
Database
SQL
Stored Procedures
USE DATABASE
How can I write a stored procedure which can switch to new databases using something like "use DBASENAME", but without knowing the dbase names before the procedure runs? The example below was my attempt to do this using SP_EXECUTESQL. The reason for this is so that I can call stored procedures within my stored procedure so that they will use the data in the desired dbase. set nocount on use demo declare @NSqlStatment as nvarchar(500) declare @DbaseName as varchar(20) print db_name() set @DbaseName = 'poports' SET @NSqlStatment = 'use ' + @DbaseName EXEC SP_EXECUTESQL @NSqlStatment print db_name() use poports print db_name() RESULTS: demo demo poports
ASKED: November 7, 2007  1:40 PM
UPDATED: December 2, 2007  12:09 PM

Answer Wiki

Thanks. We'll let you know when a new response is added.

In order to do this everything which needs to be done within the other database needs to be done in the dynamic SQL. Dynamic SQL is done out of bounds of the parent code. Using this method it would be much better to simply access the objects without the USE command.

<pre>declare @db varchar(10)
set @db = ‘db1′
declare @cmd varchar(8000)
set @cmd = ‘select * from ‘ + @db
exec (@cmd)</pre>

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following