1

Possible Duplicate:
In SQL server is there any way to get the 'use database' command to accept a variable

We can change the database by their name is no problem as below

USE master
GO

But I need this in a script and have the database name in a variable. How to make this?

select @cmd = N'use ' + @oldDb  + N';'
exec sp_executesql @cmd

That doesn't work - the current database stays the same after the execution.

Is something possible at all?

0

2 Answers 2

5

Apparently the problem is with using GO within a dynamic sql statement, because execute sql doesn't support multiple batches. Please see this link for the solution. Change Database with Dynamic SQL

1
  • I want to change the database context using T-SQL without the GO command - I have updated the script to obmit the go
    – Nam G VU
    Mar 3, 2011 at 9:24
-2

Perhaps there's a valid reason for this, but if possible I would recommend naming the DB by name in your script where required. for example

databasename.table.owner.field

1
  • It's a nice work-around. Though, my automation query script will have to replace the database name when it is changed - this shouldn't be acceptable when my script is handed to other developers in the team; they just need to enter the database name once and from then, just hit run to see the result. Thanks any way
    – Nam G VU
    Mar 10, 2011 at 4:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.