Tuesday, November 10, 2009

T-SQL to get user list for every database

Today I created a new T-SQL script that gets list of existing databases on SQL Server and via sp_helpuser queries each database for login information.


There is also used variable table @dbs which keeps database names with assigned IDs. IDs are being assigned with row_number() procedure.


It could be further developed to join logins to some temporary table etc, that would allow to see some statistics (user rights, user and database mappings).



declare @RowCnt int
declare @MaxRows int
declare @dbname nvarchar(50)

declare @dbs table
(
ID int,
[name] nvarchar(50)
)

insert into @dbs
select * from
(select row_number() over (ORDER BY [name]) as 'ID',
[name] FROM master.dbo.sysdatabases WHERE dbid > 6) as tbl1

select @MaxRows=count(*) from @dbs
select @RowCnt = 1

while @RowCnt <= @MaxRows
begin
select @dbname = [name] from @dbs where id = @RowCnt
exec('use ['+@dbname+']; EXECUTE sp_helpuser;')
Select @RowCnt = @RowCnt + 1
end

No comments:

Post a Comment