USE DB with a variable

  • 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?

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

  • Be aware that the Use statement will only apply to the dynamic query being run.


    My blog: SQL Soldier[/url]
    SQL Server Best Practices:
    SQL Server Best Practices
    Twitter: @SQLSoldier
    My book: Pro SQL Server 2008 Mirroring[/url]
    Microsoft Certified Master: SQL Server, Data Platform MVP
    Database Engineer at BlueMountain Capital Management[/url]

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

  • What's wrong with select db_name() ..?

    /Kenneth

  • 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.

  • It also works should you dare dabble with dynamic SQL.

    use tempdb

    go

    declare @sql varchar(255)

    set @sql = 'use master select db_name()'

    exec ( @sql)

    go

    /Kenneth

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply