Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL to list all the user mappings with database roles/permissions for a Login

I am looking for a t-sql script which can list the databases and and the respective roles/privileges mapped for a particular user. Using SQL Server 2008 R2.

like image 381
muddu83 Avatar asked Dec 12 '11 07:12

muddu83


People also ask

How do I get list of Logins and permissions in SQL Server?

First, move to “Object Explorer” and expand the database that you want. Next, under the database, expand the “Security” directory. Now, under Security, expand the “Users” option. This will display a list that contains all the users created in that database.

How can I get a list of all database users?

Answer: In SQL Server, there is a system view called sys. database_principals. You can run a query against this system view that returns all of the Users that have been created in SQL Server as well as information about these Users.


2 Answers

CREATE TABLE #tempww (
    LoginName nvarchar(max),
    DBname nvarchar(max),
    Username nvarchar(max), 
    AliasName nvarchar(max)
)

INSERT INTO #tempww 
EXEC master..sp_msloginmappings 

-- display results
SELECT * 
FROM   #tempww 
ORDER BY dbname, username

-- cleanup
DROP TABLE #tempww
like image 147
Walter Wildoer Avatar answered Oct 16 '22 18:10

Walter Wildoer


CREATE TABLE #tempww (

    LoginName nvarchar(max),
    DBname nvarchar(max),
    Username nvarchar(max), 
    AliasName nvarchar(max)
)

INSERT INTO #tempww 

EXEC master..sp_msloginmappings 

-- display results

declare @col varchar(1000)

declare @sql varchar(2000)

select @col = COALESCE(@col + ', ','') + QUOTENAME(DBname)

from #tempww Group by DBname

Set @sql='select * from (select LoginName,Username,AliasName,DBname,row_number() over(order by (select 0)) rn from #tempww) src

PIVOT (Max(rn) FOR DBname

IN ('+@col+')) pvt'

EXEC(@sql)



-- cleanup
DROP TABLE #tempww
like image 22
Piotr Czekaj Avatar answered Oct 16 '22 17:10

Piotr Czekaj