Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - How to get user login mappings?

I know this question has been asked before in many forms, but unfortunately, none of them helped me in this quite basic need - I'm looking for a script which takes as a parameters a particular login's name & database and return the appropriated associated roles.

For example - for the attached screen shot, when passing the script the ADMA1 user name & the fogbugzRelease database the output shoul be db_owner.

enter image description here

like image 820
user8874956 Avatar asked May 21 '26 13:05

user8874956


1 Answers

You can use below query to get database role assigned to the user

DECLARE @command nvarchar(4000) 
DECLARE @DBRole TABLE (DBName sysname, UserName sysname, RoleName varchar(255))
SELECT @command = 'use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') else prin.name end AS UserName
,isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id'

INSERT INTO @DBRole
EXEC sp_MSforeachdb @command 

SELECT * FROM @DBRole t 
WHERE t.UserName like '%YourUserName%'
and t.DBName like '%Your DB Name%'
like image 83
ASP Avatar answered May 26 '26 14:05

ASP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!