Add Users to Database Script
-
Posted on July 25, 2009 by Derek Dieter
-
0
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
DROP TABLE #Roles
END TRY BEGIN CATCH END CATCH
;WITH Substr(num, firstchar, lastchar) AS (
SELECT 1, 1, CHARINDEX(@delimiter, @UserString)
UNION ALL
SELECT num + 1, lastchar + 1, CHARINDEX(@delimiter, @UserString, lastchar + 1)
FROM Substr
WHERE lastchar > 0
)
SELECT
num,
UserName = SUBSTRING(@UserString, firstchar, CASE WHEN lastchar > 0 THEN lastchar-firstchar ELSE 8000 END)
INTO #Users
FROM Substr
;WITH Substr(num, firstchar, lastchar) AS (
SELECT 1, 1, CHARINDEX(@delimiter, @DatabaseString)
UNION ALL
SELECT num + 1, lastchar + 1, CHARINDEX(@delimiter, @DatabaseString, lastchar + 1)
FROM Substr
WHERE lastchar > 0
)
SELECT
num,
DatabaseName = SUBSTRING(@DatabaseString, firstchar, CASE WHEN lastchar > 0 THEN lastchar-firstchar ELSE 8000 END)
INTO #Databases
FROM Substr
;WITH Substr(num, firstchar, lastchar) AS (
SELECT 1, 1, CHARINDEX(@delimiter, @RolesString)
UNION ALL
SELECT num + 1, lastchar + 1, CHARINDEX(@delimiter, @RolesString, lastchar + 1)
FROM Substr
WHERE lastchar > 0
)
SELECT
num,
RoleName = SUBSTRING(@RolesString, firstchar, CASE WHEN lastchar > 0 THEN lastchar-firstchar ELSE 8000 END)
INTO #Roles
FROM Substr
DECLARE @NumUsers INT
DECLARE @NumDBs INT
DECLARE @NumRoles INT
DECLARE @UserIter INT
DECLARE @DBIter INT
DECLARE @RoleIter INT
DECLARE @UserName VARCHAR(255)
DECLARE @RoleUserName VARCHAR(255)
DECLARE @DBName VARCHAR(255)
DECLARE @RoleName VARCHAR(255)
DECLARE @SQL VARCHAR(MAX)
SET @NumUsers = (SELECT MAX(num) FROM #Users)
SET @NumDBs = (SELECT MAX(num) FROM #Databases)
SET @NumRoles = (SELECT MAX(num) FROM #Roles)
SET @UserIter = 1
SET @SQL = ”
WHILE @UserIter <= @NumUsers BEGIN SET @DBIter = 1 SET @UserName = (SELECT UserName FROM #Users WHERE num = @UserIter) --SET @SQL = 'CREATE LOGIN ' + @UserName + ' FROM WINDOWS WITH DEFAULT_DATABASE = ' + @DefaultDatabase SET @SQL = 'CREATE LOGIN ' + @UserName + ' WITH PASSWORD=N''mypassword'' MUST_CHANGE, DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON' PRINT (@SQL) SET @UserIter = @UserIter + 1 -- Add user to the databases WHILE @DBIter <= @NumDBs BEGIN SET @RoleIter = 1 SET @DBName = (SELECT DatabaseName FROM #Databases WHERE num = @DBIter) SET @SQL = 'USE ' + @DBName + '; CREATE USER ' + @UserName + ' FOR LOGIN ' + @UserName PRINT (@SQL) SET @DBIter = @DBIter + 1 WHILE @RoleIter <= @NumRoles BEGIN SET @RoleName = (SELECT RoleName FROM #Roles WHERE num = @RoleIter) -- Must remove brackets for addrolemember procedure SET @RoleUserName = REPLACE(REPLACE(@UserName, '[', ''), ']', '') SET @SQL = 'USE ' + @DBName + '; EXEC sp_addrolemember ''' + @RoleName + ''', ''' + @RoleUserName + '''' PRINT (@SQL) SET @RoleIter = @RoleIter + 1 END END END [/cc]
- Comments (RSS)
- Trackback
- Permalink
Free shipping site of all cheap green bay packers jerseys products,more items bigger discount,hurry
to collect cheap amari cooper jersey
I am now not sure where you’re getting your information, but good
topic. I needs to spend a while finding out much more or working
out more. Thanks for great information I was
searching for this information for my mission.p3148
What is size of cheap Deone Bucannon jerseys may have?
Know more about here – cheap D.J. Swearinger jerseys
What team you support? Buy Cheap New York Knicks Jerseys and save more now.
Wholesale Tennessee Titans Jerseys
Youth,mens,womens Wholesale Panthers Jerseys online,find authentic quality Wholesale Chicago
Bears Jerseys
Great place to order official baseball jerseys by Paypal.
cheap nhl hockey jerseys china
Elite/throwback/authentic/replica cheap gilbert rugby balls for you,access
our site by click: Cheap Baltimore Ravens Jerseys
What is size of cheap T. J. Jones jerseys may have?
Know more about here – toddler hockey jerseys
What is size of usa jersey wholesale may have? Know more about here – super saturday nfl
shop promotional codes
Excellent work!
Because I needed that feature I added DROP LOGIN and DROP USER – works like a charm.
Excellent script
i used and find one logical error that the roles creating for first database in the list not for the rest.
i corrected the logic with putting SET @RoleIter = 1 statement in the right place and works fine now.
here is the code:
WHILE @UserIter <= @NumUsers
BEGIN
SET @DBIter = 1
SET @UserName = (SELECT UserName FROM #Users WHERE num = @UserIter)
–SET @SQL = 'CREATE LOGIN ' + @UserName + ' FROM WINDOWS WITH DEFAULT_DATABASE = ' + @DefaultDatabase
SET @SQL = 'CREATE LOGIN ' + @UserName + ' WITH PASSWORD=N''steelwedge@123'' MUST_CHANGE, DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON'
PRINT (@SQL)
SET @UserIter = @UserIter + 1
— Add user to the databases
WHILE @DBIter <= @NumDBs
BEGIN
SET @RoleIter = 1
SET @DBName = (SELECT DatabaseName FROM #Databases WHERE num = @DBIter)
SET @SQL = 'USE ' + @DBName + '; CREATE USER ' + @UserName + ' FOR LOGIN ' + @UserName
PRINT (@SQL)
SET @DBIter = @DBIter + 1
WHILE @RoleIter <= @NumRoles
BEGIN
SET @RoleName = (SELECT RoleName FROM #Roles WHERE num = @RoleIter)
— Must remove brackets for addrolemember procedure
SET @RoleUserName = REPLACE(REPLACE(@UserName, '[', ''), ']', '')
SET @SQL = 'USE ' + @DBName + '; EXEC sp_addrolemember ''' + @RoleName + ''', ''' + @RoleUserName + ''''
PRINT (@SQL)
SET @RoleIter = @RoleIter + 1
END
END
END
Thanks
Excellent code and appreciated your time.
What if DBA wanted to rollback login creation and revoking roles?
Thanks in advance.
Banutharan.
This article is very useful for me to create – Request for Change (RFC) ->which will assign the role to user through script.