Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 How access database specified in a variable

Author  Topic 

Rafferty Uy
Starting Member

23 Posts

Posted - 2004-09-16 : 05:08:39
Hello there,

For customizability concerns, is it possible to have the database name specified in a variable? for example:

DECLARE @DBName VARCHAR(50)
SET @DBName = 'OtherDB'

SELECT * FROM [@DBName].dbo.SomeTable

Of course this SQL procedure does not work, so how do I get it to work? :)

Thanks!

-Rafferty

jen
Master Smack Fu Yak Hacker

4110 Posts

Posted - 2004-09-16 : 05:14:06
use dynamic sql

declare @sql nvarchar(100)

set @sql = 'SELECT * FROM [' + @DBName + '].dbo.SomeTable'
exec sp_executesql @sql

quote:
Originally posted by Rafferty Uy

Hello there,

For customizability concerns, is it possible to have the database name specified in a variable? for example:

DECLARE @DBName VARCHAR(50)
SET @DBName = 'OtherDB'

SELECT * FROM [@DBName].dbo.SomeTable

Of course this SQL procedure does not work, so how do I get it to work? :)

Thanks!

-Rafferty

Go to Top of Page
   

- Advertisement -