开发者

How to use T-SQL to call exec(@sql) to change current database? [duplicate]

开发者 https://www.devze.com 2023-02-14 03:33 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: In SQL server is there any way to get the 'use database' command to accept a variable
This question already has answers here: Closed 10 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消