database 如何使用 T-SQL 调用 exec(@sql) 来更改当前数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5167025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use T-SQL to call exec(@sql) to change current database?
提问by Nam G VU
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?
有什么可能吗?
回答by Bmw
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
显然问题在于在动态 sql 语句中使用 GO,因为执行 sql 不支持多批次。请参阅此链接以获取解决方案。使用动态 SQL 更改数据库
回答by Jody
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
数据库名称.table.owner.field

