We have a test database and some test logins that we would like to give db_owner access to through a script. Usually we would have to go into logins and right click on the username and go to user mapping and select the database to associate it with and give it owner access and click OK.
4 Answers
You need to do two things, both running in the context of the target database (i.e., execute USE (database)
first):
- Add that user as a login to the database:
CREATE USER [LoginName] FOR LOGIN [LoginName]
- Add that user to the role:
EXEC sp_addrolemember N'db_owner', N'LoginName'
In general, if you have SQL Server Management Studio 2005 or higher, you can go into the UI for an operation, fill out the dialog box (in this case, assigning the user to the database & adding roles), and then click the "Script" button at the top. Instead of executing the command, it will write a script for the action to a new query window.
-
1What if the user already exist just needs to be mapped to the database first and then run the sp_addrolemember SP. Can this be done? Aug 29, 2011 at 16:27
-
The mapping to the database is the first query. It assumes a login (username/password) has already been created on the server. You can check if they have already been mapped by looking at
sys.database_principals
in the target database.– TadmasAug 29, 2011 at 16:31 -
-
4It works, but according to the MSDN docs, this sproc is now deprecated. I tried doing it with ALTER ROLE as the alternative the docs suggested, but as pointed out it doesn't work with built-in roles. Any idea how this can be done without this sproc? Nov 6, 2012 at 19:51
-
I'd like to propose another solution which may help someone...
-- create the user on the master database
USE [master]
GO
CREATE LOGIN [MyUserName] WITH PASSWORD=N'MyPassword'
CREATE USER [MyUserName] FOR LOGIN [MyUserName]
GO
-- create the user on the target database for the login
USE [MyDatabaseName]
GO
CREATE USER [MyUserName] FOR LOGIN [MyUserName]
GO
-- add the user to the desired role
USE [MyDatabaseName]
GO
ALTER ROLE [db_owner] ADD MEMBER [MyUserName]
GO
-
2Perfect! Spent an hour looking for an all-in-one solution and this was it. Cheers! Jul 21, 2019 at 8:29
Use sp_addrolemember
EXEC sp_addrolemember 'db_owner', 'MyUser'
-
1I tried that one and it says Msg 15410, Level 11, State 1, Procedure sp_addrolemember, Line 75 User or role 'QA-Tester1' does not exist in this database. Aug 29, 2011 at 16:22
-
You have to add the role first then you can add the user to that role Aug 11, 2021 at 4:51
Here is how to use ALTER ROLE
with an existing server login named MyLogin
.
USE MyDatabase
CREATE USER MyLogin FOR LOGIN MyLogin
ALTER ROLE db_owner ADD MEMBER MyLogin
GO
https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-role-transact-sql