首先我使用了sp_foreachdb,但是读取它不受支持,输出也不是最好的进一步处理......
DECLARE @command varchar(1000)
SELECT @command = 'USE [?]
IF DB_ID(''?'') > 4
SELECT ''?'' as DBName, * FROM sysusers AS SU
Left Join sys.server_principals AS SP
ON SU.sid = SP.sid
WHERE SP.type = ''S''
ORDER BY SU.name'
EXEC sp_MSforeachdb @command
现在我对嵌套查询和UNION进一步了解。 但现在我得到所有用户而不仅仅是sql用户(不是系统用户)
DECLARE @Sql NVARCHAR(MAX) = NULL;
SELECT @Sql = COALESCE(@Sql + ' UNION ALL ' + CHAR(13) + CHAR(10), '' ) + 'SELECT ''' + DB.[name] + ''' AS dbname, SU.[name] COLLATE Latin1_General_CI_AS AS Username
FROM ' + QUOTENAME([name]) + '.sys.sysusers AS SU'
--INNER Join sys.server_principals AS SP'
--ON SU.sid = SP.sid
--WHERE SP.type = ''S''
--ORDER BY SU.name'
FROM master.sys.databases as DB
WHERE [database_id] > 4 AND [state] = 0;
SET @Sql = ' ' + @Sql;
--PRINT @Sql;
EXECUTE ( @Sql )
一旦我添加了注释行,“union statement”旁边就会出错...
有谁能告诉我如何正确使用“for each database”查询? :)
很多。