• Sgar... (4/16/2016)


    Andrew Ryan (7/9/2009)


    Sorry if this has been covered but as you might imagine searching for this has been problematic.

    I want to use vaariables with my USE commands.

    USE @DBName

    GO

    if I use that I get an error that points to an arbitrary line in the code.

    if I use this the database does not change but executes with no errors.

    DECLARE @DBName char(3), @X as varchar(MAX)

    SET @DBName = 'SBU'

    set @X = 'use ' + @DBName +';'

    EXEC(@X);

    I want to dynamically change which DB I am using. I could just be going about this the wrong way.

    i was talking about hardcoding database name in procedure. In my procedure @dbname will be input parameter, it cannot be hardcoded. Hope its clear now.

    Yes, that is how I interpreted your question. Did you read my reply?


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/