Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL to Map User to Database

So I'm not able to user enterprise manager to do this... If I was I wouldn't even be asking this question. So I'm wondering if there is a way through TSQL to execute a command that maps a User to a particular Database and grants them 'owner' permissions.

Thanks...

like image 334
dtrick Avatar asked May 05 '10 16:05

dtrick


People also ask

What is Sp_change_users_login?

Use sp_change_users_login to link a database user in the current database with a SQL Server login. If the login for a user has changed, use sp_change_users_login to link the user to the new login without losing user permissions.

How do I get a list of database users 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.


2 Answers

Change default database of a login:

alter login <loginname> with default_database = <dbname>; 

Create a user in a database for a given login:

use <dbname>; create user <username> from login <loginname>; 

Make an user member of db_owner group:

use <dbname> exec sp_addrolemember 'db_owner', '<username>'; 

Make a login 'dbo' of a database:

alter authorization on database::<dbname> to <loginname>; 
like image 159
Remus Rusanu Avatar answered Sep 22 '22 19:09

Remus Rusanu


Officially, you want to create a database user that is mapped to a login. To do that, you would use:

Create User <username> For LOGIN <loginname> 

This obviously requires that the login exist. After that you would then call:

exec sp_addrolemember 'db_owner', <username> 

This presumes that the account with which you are connecting to the database has privileges to add members to the db_owner role.

like image 41
Thomas Avatar answered Sep 22 '22 19:09

Thomas