sql use statement with variable

前端 未结 10 1292
花落未央
花落未央 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条回答
  •  -上瘾入骨i
    2020-11-30 09:16

    You can do this:

    Declare @dbName nvarchar(max);
    SET @dbName = 'TESTDB';
    
    Declare @SQL nvarchar(max);
    select @SQL = 'USE ' + @dbName +'; {can put command(s) here}';
    EXEC (@SQL);
    
    {but not here!}
    

    This means you can do a recursive select like the following:

    Declare @dbName nvarchar(max);
    SET @dbName = 'TESTDB';
    Declare @SQL nvarchar(max);
    
    SELECT @SQL = 'USE ' + @dbName + '; ' +(Select ... {query here}
    For XML Path(''),Type)
    .value('text()[1]','nvarchar(max)');
    
    Exec (@SQL)
    

提交回复
热议问题