我需要创建一个存储过程(1个或多个),我可以从预定作业中的主数据库(或其他数据库)调用该存储过程,以将权限(用户和权限)恢复到已从源恢复的数据库D b。我不想在源数据库级别创建用户,因为我想限制对该服务器的访问,因此需要在完成还原后执行sproc以授予访问权限。我目前有:
use (database);
if ( select objectproperty(object_id('dbo.spMaint_RestorePermissions_database'), 'IsProcedure') ) is null
exec ('create procedure dbo.spMaint_RestorePermissions_database as select 1');
go
alter procedure dbo.spMaint_RestorePermissions_database
as
set nocount on;
---- grant user permission to access database
create user [domain\userid] for login [domain\userid]
----- grant user access rights to database
exec sp_addrolemember 'db_datareader', 'domain\userid'
go
答案 0 :(得分:2)
存储过程的一个限制是它们不能包含use database;
语句。要完成您正在寻找的内容,您可以从master运行sp_executesql并传入一个tsql字符串,该字符串在特定数据库的上下文中执行sp_executesql。像这样:
--This is the tsql statement that gets executed on a specific user db.
--You would use this to build your "create proc", "alter proc", "create user", etc statements.
DECLARE @InnerSql NVARCHAR(MAX) = 'SELECT DB_NAME()'
DECLARE @DB SYSNAME = 'DatabaseName'
DECLARE @Tsql NVARCHAR(MAX) = '[' + @DB + ']..sp_executesql N''' + @InnerSql + ''''
EXEC sp_executesql @Tsql;