• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 617
  • Last Modified:

Incorrect syntax near '@DBName'

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
2 Solutions
Aneesh RetnakaranDatabase AdministratorCommented:
DECLARE @DBName VarChar(30)
Set @DBName='MyDatabase'
EXEC (' Use '+@DBName +'  ; go'  )
BudenkAuthor Commented:
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?
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now