How do I set the database name dynamically in a SQL Server stored procedure?
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.