sql use statement with variable

前端 未结 10 1304
花落未央
花落未央 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:27

    -- If you are using a variable for the database name. 
    -- Try something like this. 
    
    DECLARE @DBName varchar(50)
    Set @DBName = 'Database1'; /*  could be passed in by a parameter. */
    
    IF( @DBName = 'Database1')
    Begin
        USE [Database1];
    SELECT  FROM Table1;
    End
    
    IF( @DBName = 'Database2')
    Begin
    USE [Database2];
    SELECT  FROM Table2;
    End
    
    IF( @DBName is null)
    Begin
    USE [Database1];
    End
    

提交回复
热议问题