January 4, 2007 at 3:29 pm
Is it possible to dynamically set the database with variable?
I tried...
Declare @db varchar(15)
set @db = 'Databasename'
USE @db
I got a syntax error. Can this be done? What am I missing?
January 4, 2007 at 3:46 pm
Execute this from a database other than Northwind.
DECLARE @DBName varchar(100), @sqlStr varchar(1000)
SET @DBName = 'NorthWind'
SET @sqlstr = 'USE ' + @DBName + ';'
SET @sqlstr = @sqlstr + 'SELECT COUNT(*) FROM Products'
EXEC(@sqlstr)
January 4, 2007 at 11:14 pm
Be aware that the Use statement will only apply to the dynamic query being run.
January 5, 2007 at 3:26 am
While on the topic, sometimes you want to know what database you're in:
declare @dbname varchar(30)
set @dbname=(select d.name
from master.dbo.sysprocesses p,master.dbo.sysdatabases d
where p.spid=@@spid and p.dbid=d.dbid)
January 5, 2007 at 3:29 am
What's wrong with select db_name() ..?
/Kenneth
January 5, 2007 at 3:36 am
Indeed! The BOL doesn't say that the dbid parameter is optional. And I never thought about just leaving it out to get at the current db name. Thus my convoluted solution.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply