如何将变量传递给SP,并在循环或游标中使用它?

时间:2017-10-10 21:19:09

标签: sql-server loops tsql dynamic

脚本的原因有点复杂,但是意味着允许较低级别的用户请求DB备份,解密和恢复到QA / UAT环境并使用TDE重新加密,然后获得QA / UAT用户动态添加(有时会更改)。

我使用动态SQL来获取SP中传递的参数,然后根据SP中的QA或UAT @env变量运行这两个语句中的一个。恢复和加密数据库之后,我需要删除PROD用户角色,并在可能的情况下动态添加QA或UAT用户角色,方法是将它们拉入由DB分隔的表中。

以下是用户在恢复QA / UAT数据库后删除/重新添加部分。这将是SP的结尾,以及我正在尝试将@db参数传递给@db运行并运行:

--CURSOR TO REMOVE SQL USERS AND ROLES AFTER RESTORE: DIFFERENCE DUE TO PROD VS QA/UAT USER ROLES
DECLARE @oldusername VARCHAR(64)
  DECLARE c1 CURSOR FOR 
    SELECT name   
    FROM sysusers
    WHERE name NOT IN('dbo','guest','INFORMATION_SCHEMA','sys','public')
     and name not like 'db_%'
  OPEN c1
  FETCH next FROM c1 INTO @oldusername
  WHILE @@fetch_status <> -1
   BEGIN
        EXEC dbo.sp_revokedbaccess @oldusername
     FETCH next FROM c1 INTO @oldusername
   END
CLOSE c1
DEALLOCATE c1;
--CURSOR TO ADD BACK WIN/SQL USERS AND ROLES AFTER RESTORE. DIFFERENCE DUE TO PROD VS QA/UAT USER ROLES
DECLARE @username VARCHAR(64)
DECLARE @associatedrole VARCHAR(100)
  DECLARE c2 C]URSOR FOR 
    SELECT username,AssociatedRole
    FROM dba.dbo.db_users
    WHERE DBname='+@db+'
  OPEN c2
  FETCH next FROM c2 INTO @username,@AssociatedRole
  WHILE @@fetch_status <> -1
   BEGIN
       --print 'EXEC sp_addrolemember '+@associatedrole+', '+@username+''
       if not exists(select * from sys.database_principals where name = @username) 
       begin
       EXEC sp_adduser @username;
       end
       EXEC sp_addrolemember @associatedrole,@username;
     FETCH next FROM c2 INTO @username,@AssociatedRole
   END
CLOSE c2
DEALLOCATE c2;

0 个答案:

没有答案