Incorrect syntax near '@DBName'

Posted on 2007-10-18
Medium Priority
Last Modified: 2008-09-08
I am trying to create variable and assign database name to it and run it on 'Use' command like below.
It doesn't work.
How to make it work?

Here is the error that I get: Line 3: Incorrect syntax near '@DBName'.

DECLARE @DBName VarChar(30)
Set @DBName='MyDatabase'
Use @DBName
Question by:Budenk
LVL 75

Accepted Solution

Aneesh Retnakaran earned 252 total points
ID: 20103584
DECLARE @DBName VarChar(30)
Set @DBName='MyDatabase'
EXEC (' Use '+@DBName +'  ; go'  )

Author Comment

ID: 20103670
I actually have long scripts folowing that 'Use' command.
If I am using 'Exec', I need to put that long script inside the 'exec' command which is not good
Do you have another solution?
LVL 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 248 total points
ID: 20104645
unfortunately, you have no choice, but either have the database correctly set up as connected database (instead of the use), or get the entire script into EXEC() as indicated by aneeshattingal.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Suggested Courses

839 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