开发者

In SQL Server 2005, how can I use database_b, do something, then use the old db database_a in TSQL?

In SQL Server 2005, how can I use database_b, do something, then use the old db database_a in TSQL? The following is my code but there is some problem with it. Who can help me to identity the problem? Great thanks.

DECLARE @old_database_name VARCHAR(200)
SET @old_database_name = db_name()

use my开发者_StackOverflow中文版database

create table t1(id int identity(1,1))

use @old_database_name


You'll need to use dynamic sql to do this.

e.g.

-- Do stuff in current DB here

EXECUTE ('USE mydatabase; create table t1(id int identity(1,1));')

-- Do more stuff in current DB here. This context will not have changed since before the EXECUTE statement


Why are you even using USE statements for this?

create table mydatabase.dbo.t1(id int identity(1,1)) 


This is similar to AdaTheDev's "EXECUTE" example, but uses sp_executesql :

-- Do stuff in current DB here

EXECUTE mydatabase..sp_executesql N'create table t1(id int identity(1,1));'

-- Do more stuff in current DB here. This context will not have changed since before the EXECUTE statement
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜