有没有办法从变量中选择数据库? [英] Is there a way to select a database from a variable?
问题描述
是否可以从变量中选择数据库?
Is there a way to select a database from a variable?
Declare @bob as varchar(50);
Set @bob = 'SweetDB';
GO
USE @bob
推荐答案
不幸的是,没有。
除非您可以将其余批处理作为动态SQL执行。
Unless you can execute the rest of your batch as dynamic SQL.
使用 execute
以动态执行SQL将更改 execute
语句范围的上下文,但不会对您从中执行 execute
语句的范围。
Using execute
to dynamically execute SQL will change the context for the scope of the execute
statement, but will not leave a lasting effect on the scope you execute the execute
statement from.
换句话说,这是:
DECLARE @db VARCHAR(100)
SET @db = 'SweetDB'
EXECUTE('use ' + @db)
不会永久设置当前数据库,但是如果您更改了上述代码,则如下:
Will not set the current database permanently, but if you altered the above code like this:
DECLARE @db VARCHAR(100)
SET @db = 'SweetDB'
EXECUTE('use ' + @db + ';select * from sysobjects')
select * from sysobjects
然后得出这些结果两个查询会有所不同(假设您已经不在SweetDB中),因为在 execute
内部执行的第一个选择在SweetDB中执行,但是第二个则没有。
Then the result of those two queries will be different (assuming you're not in SweetDB already), since the first select, executed inside execute
is executing in SweetDB, but the second isn't.
这篇关于有没有办法从变量中选择数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!