Getting all databases which a sql logon can connect

Posted on

Question :

I need to know all databases in a SQL Server on which a user can connect. With sys.databases I get all databases and with sys.server_principals or sys.syslogins I get all server logons. But I can’t find a table which contains a connection between these tables. Has anyone an idea how to solve this? Thanks.

Answer :

You should be able to do something like this:

EXECUTE AS login = 'loginname';

SELECT name
FROM sys.databases
WHERE HAS_DBACCESS(name) = 1;

REVERT;

For reference see EXECUTE AS and HAS_DBACCESS

This should put you in the right direction:

DECLARE @results TABLE (
    database_name sysname,
    db_user_name sysname,
    login_name sysname
);

INSERT @results
EXEC sp_MsForEachDB '
USE [?];
SELECT DB_NAME() AS database_name,
    dp.name AS db_user_name, 
    sp.name AS login_name
FROM sys.database_principals dp
INNER JOIN sys.server_principals sp 
    ON sp.sid = dp.sid
';

SELECT *
FROM @results;

P.S. sp_MsForEachDB is ugly, undocumented and unreliable, but it’s just to show you how the information is stored in each individual database.

Leave a Reply

Your email address will not be published.