sql use statement with variable

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

    try this:

    DECLARE @Query         varchar(1000)
    DECLARE @DatabaseName  varchar(500)
    
    SET @DatabaseName='xyz'
    SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table1'
    EXEC (@Query)
    
    SET @DatabaseName='abc'
    SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table2'
    EXEC (@Query)
    

提交回复
热议问题