question

Govin avatar image
Govin asked

SQL Server - database access information

I need to pull out how many databases are accessible for a particular user in SQL Server 2000/2005 using a query. Any help is appreciated. Thank You

sql-server-2005sql-server-2000
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Matt Whitfield avatar image
Matt Whitfield answered

When you run this on a particular database in 2005, it will return you the users with permission to connect, listing as the database name, the login name and the database user name.

SELECT DB_NAME() AS DatabaseName, [sp].[name] AS LoginName, [dp].[name] AS DatabaseUserName
FROM   [sys].[server_principals] AS [sp]
       INNER JOIN
       [sys].[database_principals] AS [dp]
       ON [dp].[sid] = [sp].[sid]
       INNER JOIN
       [sys].[database_permissions] AS [dp1]
       ON [dp1].[grantee_principal_id] = [dp].[principal_id]
WHERE  [dp1].[type] = 'CO';

This is the 2000 equivalent:

SELECT DB_NAME() AS DatabaseName, SUSER_SNAME([s].[sid]) AS LoginName, [s].[name] AS DatabaseUserName
FROM   [sys].[sysusers] [s]           
WHERE  [hasdbaccess] = 1 AND SUSER_SNAME([s].[sid]) IS NOT NULL

You can then execute this on the multiple databases however suits you best - either using SSMS 2008's multiple execution or some third party tool.

Having looked at Kev's answer, here's a combination of the two:

create TABLE #dbnames (dbname [sysname] NULL, LoginName [sysname] NULL, DatabaseUserName [sysname] NULL)
insert into #dbnames
EXEC sp_MSforeachdb 'SELECT ''?'' AS DatabaseName, SUSER_SNAME([s].[sid]) AS LoginName, [s].[name] AS DatabaseUserName
FROM   [?]..[sysusers] [s]          
WHERE  [hasdbaccess] = 1 AND SUSER_SNAME([s].[sid]) IS NOT NULL'

select * from #dbnames

drop table #dbnames
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kev Riley avatar image
Kev Riley answered

Here's a solution that works without having to run against multiple databases. It also works on both 2000 and 2005, just because the system table is included in 2005 for backwards compatability!

it also uses the undocumented (and therefore unsupported) stored proc sp_MSforeachdb

create table #dbnames (dbname varchar(100))
insert into #dbnames
exec sp_MSforeachdb 'select ''?'' from sysusers where name = ''MyUser'' and hasdbaccess = 1'

select dbname from #dbnames

drop table #dbnames
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.