using a local variable in the USE statement

  • Hi,

    I'm trying to use a local variable in the USE statement but can't seem to get the correct syntax.

    Here's what I'm trying ---

    declare @db SYSNAME

    set @db =

    (select TOP 1 Name from dbo.sysdatabases

    where name like 'CCM%'

    order by crdate DESC )

    USE @db

    select * from [dbo].[device]

     

    There are several databases stored on the server begining with CCM ( CCM0301, CCM0302, etc).  I need the data from the most recent one. 

    Thanks,

    Tom

     

  • Tac,
     
    Haven't tested this but should (may?) work...
     
    declare @db SYSNAME

    set @db =

    (select TOP 1 Name from dbo.sysdatabases

    where name like 'CCM%'

    order by crdate DESC )

    EXEC ('USE '+ @db)

    select * from [dbo].[device]

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • declare @db SYSNAME

    set @db =

    (select TOP 1 Name from dbo.sysdatabases

    where name like 'CCM%'

    order by crdate DESC )

    exec ('USE '+@db+';select * from [dbo].[device]')

  • That works, thanks for the help

Viewing 4 posts - 1 through 3 (of 3 total)

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