How to create a script for creation of users and roles in a DB?

Hi all,

I was looking to create a script for users and roles of my database so that I can run the script whenever I am in need and if it exist it will drop and recreate again. What I am looking now is how to create the script for users and roles. I am using sql sever.

Thank you in advance. 




Answer this question

How to create a script for creation of users and roles in a DB?

  • kiran1234

    Any idea please even if this is not possible with the techinology we have right now

  • Albertods

    What database are you using

    If SQL Server you can create a text file with the CREATE USER command to create users

    http://msdn2.microsoft.com/en-us/library/ms173463.aspx

    And CREAT ROLE to create roles:

    http://msdn2.microsoft.com/en-us/library/ms187936.aspx

  • JakeGpb

    Even the procedure that I was following to create scripts for other objects like tables and stored procedures does not work for roles and users. Please help me in this regards.

    Thank you. 



  • David Ghikas

    Hi Guys,

    I solved it in this way:

    if not exists (select * from dbo.sysusers where name = N'userName')

    EXEC sp_grantdbaccess N'userName', N'userName'

    GO

    exec sp_addrolemember N'db_datareader', N'userName'

    GO

    exec sp_addrolemember N'db_datawriter', N'userName'

    GO

    exec sp_addrolemember N'db_ExecuteDBNameProcedures', N'userName

    GO

    if not exists (select * from dbo.sysusers where name = N'db_ExecuteDBNameProcedures')

    EXEC sp_addrole N'db_ExecuteDBNameProcedures'

    GO

    This code is being created from the DB automatically by clicking the create script option.

    Any way thank you for your help!



  • How to create a script for creation of users and roles in a DB?