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>
精彩评论