The following script will add users to a database by first creating a logon for the Database Server then add user entries for each of the databases you want to give access to. Also specified are the role members for each database. Add User Using Windows Authentication [cc lang=”sql”] — Create user windows Authentication CREATE LOGIN [YourDomainNameJohnJacobs] FROM WINDOWS WITH DEFAULT_DATABASE = [YourDatabaseHere]; GO — Add User to first database USE YourDatabaseHere; CREATE USER JohnJacobs FOR LOGIN [YourDomainNameJohnJacobs]; EXEC sp_addrolemember ‘db_datareader’, ‘JohnJacobs’ EXEC sp_addrolemember ‘db_datawriter’, ‘JohnJacobs’ — Add User to second database USE YourSecondDatabaseHere; CREATE USER JohnJacobs FOR LOGIN [YourDomainNameJohnJacobs]; EXEC sp_addrolemember ‘db_datareader’, ‘JohnJacobs’ EXEC sp_addrolemember ‘db_datawriter’, ‘JohnJacobs’ [/cc] Add User Using SQL Authentication [cc lang=”sql”] — Create user for SQL Authentication CREATE LOGIN JohnJacobs WITH PASSWORD = ‘JinGleHeimerSchmidt’ ,DEFAULT_DATABASE = [YourDatabaseHere] GO — Add User to first database USE YourDatabaseHere; CREATE USER JohnJacobs FOR LOGIN JohnJacobs; EXEC sp_addrolemember ‘db_datareader’, ‘JohnJacobs’ EXEC sp_addrolemember ‘db_datawriter’, ‘JohnJacobs’ GO — Add User to second database USE YourSecondDatabaseHere; CREATE USER JohnJacobs FOR LOGIN JohnJacobs; EXEC sp_addrolemember ‘db_datareader’, ‘JohnJacobs’ EXEC sp_addrolemember ‘db_datawriter’, ‘JohnJacobs’ [/cc] To automate the creation use the script below. It will print out the statements so you can copy and paste them into SSMS. [cc lang=”sql”] SET NOCOUNT ON; DECLARE @UserString VARCHAR(8000) DECLARE @DatabaseString VARCHAR(8000) DECLARE @DefaultDatabase VARCHAR(255) DECLARE @RolesString VARCHAR(8000) DECLARE @delimiter CHAR(1) SET @UserString = ‘[yourdomainyouruser],[yourdomainyouruser2]’ SET @DatabaseString = ‘[AdventureWorks2012],[ReportServer]’ SET @DefaultDatabase = ‘[AdventureWorks2012]’ SET @RolesString = ‘db_datareader,db_datawriter’ SET @delimiter = ‘,’ BEGIN TRY DROP TABLE #Users DROP TABLE #Databases […]
Continue reading ...