Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server 2008 finding databases owned by a specific user

Tags:

sql-server

I'm going to create something like Visual Studio "Add Connection" box, my users can enter database server name, username & password, and then they can get a list of available databases (only for the entered username/password) or an error should be displayed if entered information is not correct. I've used following code which returns all databases in server:

            using (var con = new SqlConnection("Data Source=" + txtServername.Text + "; User ID=" + txtUsername.Text + ";Connect Timeout=200;pooling=false;Password=" + txtPassword.Text))
        {
            con.Open();
            DataTable databases = con.GetSchema("Databases");
            foreach (DataRow database in databases.Rows)
            {
                String databaseName = database.Field<String>("database_name");
                short dbID = database.Field<short>("dbid");
                DateTime creationDate = database.Field<DateTime>("create_date");
            }
        }

how can I limit results to databases owned by specified user?

like image 324
Ali_dotNet Avatar asked Feb 18 '26 03:02

Ali_dotNet


1 Answers

You could use this query (from this article) and add the WHERE clause you need on the owner_sid :

SELECT name, SUSER_SNAME(owner_sid)
FROM   sys.databases

For database granted access enumeration, following that thread, you can use this query, and add the needed WHERE statement :

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

INSERT INTO #tempww 
EXEC master..sp_msloginmappings 'sa' -- REPLACE IT BY YOUR USERNAME PARAMETER

-- display results
SELECT DBname
FROM   #tempww 
WHERE LoginName='sa' -- REPLACE IT BY YOUR USERNAME PARAMETER
ORDER BY dbname, username

-- cleanup
DROP TABLE #tempww
like image 117
cubitouch Avatar answered Feb 21 '26 15:02

cubitouch



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!