SQL Server – Using sp_addrolemember in Stored Procedure for Different Database

sql serversql-server-2012t-sql

I have a stored procedure to restore the latest backup of a prod database to an acceptance database. Once it's restored I need to grant a user read access to the database.

Use statements are not allowed in stored procedures, and both ALTER ROLE (it's a SQL Server 2012 box) and sp_addrolemember don't take a target database parameter.

Ideas?

Best Answer

EXEC('USE mydb;ALTER ROLE myRole ADD MEMBER myMember;');

But I am not quite sure what you are trying to achieve. After restoring a database to a different server, you need to fix the link between users and logins. For that you can execute this in your database:

ALTER USER myUser WITH LOGIN myLogin;

Or use the same EXEC('USE...') method shown above with that ALTER USER statement. That should get you where you need to be. All the database related permissions are stored in the database itself, so they get restored with the database.