开发者

Run generated use DB command in SQL Server

开发者 https://www.devze.com 2023-02-20 05:23 出处:网络
I have multi databases in SQL Server. And database design such as \"Database1\" \"Database1_Tmp\", \"Database2\", \"Database2_Tmp\" e.g.

I have multi databases in SQL Server.

And database design such as "Database1" "Database1_Tmp", "Database2", "Database2_Tmp" e.g. and in my sql command I want to execute com开发者_C百科mand on current Database and some of commands on selected Database's tmp pair.

I wrote a SQL query as below but it gives me an error

Incorrect syntax near '@db_Blobname'.

How to write a command to change current Db to running command

thanks

..........
---command for DatabaseX
........................
--trying to change current DatabaseX to DatabaseX_Tmp to run command on
    DECLARE @db_Blobname VARCHAR( 255)
    SET @db_Blobname = (SELECT DB_NAME())
    SET @db_Blobname = @db_Blobname+ '_Tmp'
    PRINT @db_Blobname
    USE  @db_Blobname
    GO
............


You can use exec or sp_executesql to do what you want. But beware: It is not enough to wrap the USE inside the dynamic sql. You have to encapsulate the whole statements you want to do on the other database in this dynamic sql call. Citing from the exec page:

Changes in database context last only until the end of the EXECUTE statement. For example, after the EXEC in this example, the database context is master:

USE master EXEC ('USE pubs') SELECT * FROM authors

So your code looks something like this, assuming you have a table "foo" in your database:

DECLARE @db_Blobname VARCHAR( 255)
DECLARE @stmnt VARCHAR(8000)
SET @db_Blobname = (SELECT DB_NAME())
SET @db_Blobname = @db_Blobname+ '_Tmp'
SET @stmnt = 'USE '+@db_Blobname+'; SELECT * FROM foo' 
EXEC (@stmnt)
GO
0

精彩评论

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