目前,必须分别为SQL Server实例的每个数据库执行sp_helpuser
。
有没有人有一个脚本可以同时为所有数据库提供sp_helpuser
输出?
答案 0 :(得分:0)
你可以像下面这样实现它。不确定SQL Server 2012但适用于SQL Server 2008 R2。提及原因sp_msforeachdb
是未记录的SP,并且不保证在将来的版本中有效。
sp_msforeachdb 'use [?] print ''?''; exec sp_helpuser;';
修改强>
请参阅以下帖子,并附上确切的代码示例。这正是您正在寻找或试图实现的目标。 TSQL: Audit user roles for all databases
<强> EDIT1:强> 我提到的帖子中的完整代码。在SQL2008R2中尝试过自己并且充满魅力。
IF OBJECT_ID('tempdb..#user_table') IS NOT NULL
BEGIN
DROP TABLE #user_table;
END;
-- tmp Table to hold the user data
CREATE TABLE #user_table
(
ServerName NVARCHAR(100) NULL,
[Database] NVARCHAR(256) NULL,
UserName NVARCHAR(128) NOT NULL,
GroupName NVARCHAR(128) NULL,
LoginName NVARCHAR(128) NULL,
DefDBName NVARCHAR(256) NULL,
DefSchemaName NVARCHAR(100) NULL,
UserID INTEGER NOT NULL,
[SID] UNIQUEIDENTIFIER NULL
);
DECLARE @sql NVARCHAR(MAX);
SET @sql = '
DECLARE @name SYSNAME,
@sql_string NVARCHAR(MAX);
-- Cursor containing all users for the current database context
DECLARE usr_name CURSOR READ_ONLY FOR SELECT [name]
FROM sysusers
WHERE hasdbaccess = 1
AND [name] NOT LIKE ''#%''
AND [name] NOT IN (''guest'');
OPEN usr_name;
FETCH NEXT FROM usr_name INTO @name;
WHILE (@@FETCH_STATUS = 0) -- This loop processes each database
BEGIN
-- if it''s a windows login surround with square brackets
IF (@name LIKE ''%\%'')
BEGIN
SET @name = ''['' + @name + '']'';
END
SET @sql_string = N''EXEC sp_helpuser '' + @name;
INSERT INTO #user_table
(
UserName,
GroupName,
LoginName,
DefDBName,
DefSchemaName,
UserId,
[SID]
)
EXEC(@sql_string);
-- Add Server & database name to dataset
UPDATE #user_table
SET ServerName = @@SERVERNAME,
[Database] = DB_NAME()
WHERE ServerName IS NULL
AND [Database] IS NULL;
-- Get the next database user
FETCH NEXT FROM usr_name INTO @name; -- Get next user
END
-- Clean up
CLOSE usr_name;
DEALLOCATE usr_name;';
-- Add USE database statement to change db context
SET @sql = 'USE ?; ' + @sql;
-- Execute the string for each database
EXEC sp_MSforeachDB @sql;
SELECT *
FROM #user_table
ORDER BY LoginName, [Database];