2

In TSQL I frequently use the use (excuse me for the wordplay):

use choosenOne

set the choosenOne database as active database. Suppose now something like:

DECLARE @NewDB varchar(255) 
SET @NewDB = 'choosenOne'

I want dinamically compose a valid use command, but I have no luck, since these codes aren't working:

use @NewDB          -- Incorrect syntax near '@NewDB'.
EXEC('use '+@NewDB) -- No runtime error but no change of db is performed

What is the right way?

3
  • A change of db is actually performed. It just is only valid for the child scope and gets changed back when the scope exits. Commented May 29, 2013 at 11:23
  • 1
    This post provides a detailed solution to this problem: stackoverflow.com/questions/727788/… Commented May 29, 2013 at 11:30
  • In addition to the solution in the question that J Tolley linked to, SQLCMD scripting variables are intended for exactly this scenario. Commented May 29, 2013 at 19:14

1 Answer 1

1

You should put your query into EXEC command after 'use '+@NewDB:

DECLARE @NewDB varchar(255) 
SET @NewDB = 'choosenOne'
EXEC('use '+@NewDB + '
 ...............')
Sign up to request clarification or add additional context in comments.

1 Comment

I was looking for a more elegant solution. Too many quotes in the real query and really error prone and unreadable solution in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.