Variables with Use statements.

  • Does anyone know if it's possible to use a variable with a USE statement?  ie:

    declare @dbname varchar(100)

    set @dbname = 'Some Database'

    use @dbname

    dbcc shrinkfile ('File', Size)

     

  • No, I don't think so. I've always had to use conditionals, e.g.

    if @dbase = 'foo' use foo

    if @dbase = 'bar' use bar

  • I was hoping it wouldn't come to that.  Thanks for the input.

  • Why do you want to do exactly?

  • declare @dbname varchar(100)

        set @dbname = 'Some Database'

    DECLARE @sql VARCHAR(8000)

        SET @sql = 'use ' + @dbname

                 + ' dbcc shrinkfile (''File'', Size)'

       EXEC (@SQL)

    ...should work for what you identified but, like Remi said, what is it you really want to do?

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

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

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