我正在使用SQL Server 2008 R2和SQL Server 2014 ...
我正在尝试运行脚本来生成另一个脚本,以便我可以执行SQL Server的存储过程sp_droprolemember
。我想在所有数据库上运行以下查询:
SELECT
user_name([member_principal_id]) as [Username],
User_Name([role_principal_id]) as [Role],
'EXEC sp_droprolemember N'''+ User_Name([role_principal_id]) +''', N''' + user_name([member_principal_id]) +''''
FROM
sys.database_role_members
WHERE
User_Name([role_principal_id]) = 'db_datareader'
我知道sp_MSforeachdb
但是我很难让它与查询一起工作......(上帝!我讨厌T-SQL连接字符串的方法!)
任何人都可以用正确的方式帮助我吗?
谢谢!
答案 0 :(得分:0)
可能是这样的......
Declare @Sql Nvarchar(max), @DBUser SYSNAME;
Declare Cur CURSOR LOCAL FAST_FORWARD FOR
Select user_name([member_principal_id])
from sys.database_principals p
INNER JOIN sys.database_role_members r ON p.principal_id = r.member_principal_id
WHERE p.type_desc IN ('SQL_USER', 'WINDOWS_USER')
AND p.name NOT IN ('dbo','guest','INFORMATION_SCHEMA','sys')
AND User_Name([role_principal_id]) = 'db_datareader'
OPEN Cur
FETCH NEXT FROM Cur INTO @DBUser
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @Sql = N'EXEC sp_droprolemember N''db_datareader'' , @DBUser'
Exec sp_executesql @Sql ,N'@DBUser SYSNAME' , @DBUser
FETCH NEXT FROM Cur INTO @DBUser
END
CLOSE Cur
DEALLOCATE Cur;