Incorrect syntax near '@DBName'

Posted on 2007-10-18
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

    DECLARE @DBName VarChar(30)
    Set @DBName='MyDatabase'
    EXEC (' Use '+@DBName +'  ; go'  )

    Author Comment

    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 142

    Assisted Solution

    by:Guy Hengel [angelIII / a3]
    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

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
    Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
    Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
    Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

    728 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

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now