tags:

views:

40

answers:

2

I'm working on a SQL script where 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.

+1  A: 

SQL Server will not let you put a variable in there, this question has come up a number of times before, looking for the duplicate.

Andrew
A: 

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)
David