开发者

In T-SQL can you use a variable with the USE command

开发者 https://www.devze.com 2022-12-19 09:08 出处:网络
I\'m working on a SQL script whe开发者_JS百科re I need to refer to the database name in multiple stops. This script will be used to run against different databases so I wanted to store the database na

I'm working on a SQL script whe开发者_JS百科re I need to refer to the database name in multiple stops. This script will be used to run against different databases so I wanted to store the database name in a variable so you only need to change the name in one location in the script.

The main problem I have with this script is with the USE command. So the code looks like.

DECLARE @DBName varchar(50)
SET @DBName = '[master]'

USE @DBName

SQL doesn't like this. Is there a way to do this.

Thanks for the help.


You can do something like this

declare @dbname varchar(250)
declare @Sql varchar(250)

set @dbname='PMDB'

SELECT @Sql ='select * from ' + @dbname + '.dbo.Account'


EXEC(@Sql)


The way I do this is not very elegant, but it works just fine

if @DBName = 'DB1'
    <query with DB1>
else
    <query with DB2>
0

精彩评论

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

关注公众号