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'u开发者_Go百科se ' + @oldDb + N';'
exec sp_executesql @cmd
That doesn't work - the current database stays the same after the execution.
Is something possible at all?
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
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
精彩评论