Set database name dynamically in SQL Server stored procedure?

前端 未结 3 1463
情书的邮戳
情书的邮戳 2020-12-03 19:51

How do I set the database name dynamically in a SQL Server stored procedure?

3条回答
  •  一整个雨季
    2020-12-03 20:21

    Stored Procedures are database specific. If you want to access data from another database dynamically, you are going to have to create dynamic SQL and execute it.

    Declare @strSQL VarChar (MAX)
    Declare @DatabaseNameParameter VarChar (100) = 'MyOtherDB'
    
    SET @strSQL = 'SELECT * FROM ' + @DatabaseNameParameter + '.Schema.TableName'
    

    You can use if clauses to set the @DatabaseNameParameter to the DB of your liking.

    Execute the statement to get your results.

提交回复
热议问题