How to use variable with use statement

Posted on 2009-05-08
Last Modified: 2012-05-06

I have a script that I'm working on that uses a variable referencing the
database name (@DBName).  When I try to use this in the form of  "USE
@DBName", it doesn't work.  If I use an nvarchar datatype and create a
string (like the following);

DECLARE @SQL nvarchar(2000)
DECLARE @DBName nvarchar(200)

SET @DBName='TestDatabase'

SET @SQL = 'USE ' + @DBName
EXEC sp_sqlexec @SQL

The script runs, but the script remains focused on the master.

Is there any way to specify USE with a variable?

Question by:RIVAGHI
LVL 75

Assisted Solution

by:Aneesh Retnakaran
Aneesh Retnakaran earned 100 total points
ID: 24341797
the dynamic sql has a different scope, and the scope come back to the current db; so whatever you need to accomplish to be done on  the other db, you should put those script inside that @sql variable and run it
LVL 31

Accepted Solution

RiteshShah earned 120 total points
ID: 24341927
you can't change focus but yes, you can do your task as Aneesh said, have a look at following script.
 though you are in MASTER database but can get results of Adventureworks database.

DECLARE @SQL nvarchar(2000)
DECLARE @DBName nvarchar(200)
SET @SQL = 'USE ' + @DBName + ';'
EXEC sp_sqlexec @SQL

Open in new window

LVL 40

Assisted Solution

Sharath earned 120 total points
ID: 24342058
In Ritesh code, you can try like this. Slightly modified his code for your requirement.

DECLARE @SQL nvarchar(2000)
DECLARE @DBName nvarchar(200)
SET @DBName='AdventureWorks'
SET @SQL = 'USE ' + @DBName + ' SELECT * FROM SYS.Objects'
EXEC sp_sqlexec @SQL
You can also try with three part name.

DECLARE @SQL nvarchar(2000)
DECLARE @DBName nvarchar(200)
SET @DBName='AdventureWorks'
SET @SQL = ' SELECT * FROM + @DBName + '.SYS.Objects'
EXEC sp_sqlexec @SQL
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

LVL 42

Assisted Solution

pcelba earned 100 total points
ID: 24343280
All the above written by Sharath is correct. If you really need to swith the database then you have to do it explicitly. Let suppose your database count is not infinite, so the only solution is:

DECLARE @DBName nvarchar(200)
SET @DBName='YourDatabase'
IF @DBName = 'Master'
   USE Master
ELSE IF @DBName = 'Model'
   USE Model
ELSE IF @DBName = 'YourDatabase'
   USE YourDatabase
   PRINT "Invalid Database name"
-- Remember the USE statement is not allowed in stored procedures, functions, and triggers

Open in new window

LVL 75

Assisted Solution

by:Anthony Perkins
Anthony Perkins earned 60 total points
ID: 24344001
You can also preface all objects with the database name and owner, that way you do not have to change databases.  This also means you would have to enable cross database ownership chaining.

Author Comment

ID: 24404500
Thank you all !!

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Change variables in SQL table 6 94
MessageHandler Database in SQL way too large 4 47
Query 14 57
Addition to SQL for dynamic fields 6 47
by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
In an interesting question ( here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

828 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