sql use statement with variable

前端 未结 10 1310
花落未央
花落未央 2020-11-30 08:23

I\'m trying to switch the current database with a SQL statement. I have tried the following, but all attempts failed:

  1. USE @DatabaseName
  2. EXEC sp_sqlexe
10条回答
  •  不知归路
    2020-11-30 09:16

    I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.

    The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.

    GOTO ScriptRunner
    
    ScriptExecutes:
    
    --------------------ACTUAL SCRIPT--------------------
    -------- Will be executed in DB1 and in DB2 ---------
    --TODO: Your script right here
    
    ------------------ACTUAL SCRIPT ENDS-----------------
    
    GOTO ScriptReturns
    
    ScriptRunner:
        USE DB1
        GOTO ScriptExecutes
    
    ScriptReturns:
        IF (db_name() = 'DB1')
        BEGIN
            USE DB2
            GOTO ScriptExecutes
        END
    

    With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.

提交回复
热议问题