Skip to content

Instantly share code, notes, and snippets.

@niaher
Created July 25, 2013 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niaher/6077972 to your computer and use it in GitHub Desktop.
Save niaher/6077972 to your computer and use it in GitHub Desktop.
Creates SQL login and user for a database. The user is created with 3 roles: db_executor, db_datareader, db_datawriter.
/*------------------------------------------------------------------------------------
Server login
-----------------------------------------------------------------------------------*/
if not exists (select 1 from sys.server_principals where name = N'MyDatabaseUser')
create login [MyDatabaseUser]
with password = 'password',
default_database = [MyDatabase],
check_policy = off,
check_expiration = off
go
/*------------------------------------------------------------------------------------
MyDatabase user
-----------------------------------------------------------------------------------*/
use [MyDatabase]
go
if exists (select 1 from sys.sysusers where name = N'MyDatabaseUser')
drop user [MyDatabaseUser]
go
create user [MyDatabaseUser] for login [MyDatabaseUser] with default_schema=[dbo]
-- db_executor role might need to be created manually.
if not exists (select 1 from sys.database_principals where name = 'db_executor')
begin
-- Create a db_executor role
create role db_executor
-- Grant execute rights to the new role
grant execute to db_executor
end
go
execute sp_addrolemember @rolename = N'db_executor', @membername = N'MyDatabaseUser';
execute sp_addrolemember @rolename = N'db_datareader', @membername = N'MyDatabaseUser';
execute sp_addrolemember @rolename = N'db_datawriter', @membername = N'MyDatabaseUser';
go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment