13

How (in SQL Server) to create a database and create a user and this user will be an admin on this database only with SQL script? I mean this user can not do/access any thing out side this database!

and is it possible to create user that has only can add, update/edit or delete data from tables and nothing else?

I know how to do that in MySQL, but not sure how with SQL Server!

2 Answers 2

25

Assuming that you are using windows auth with a login 'domain\user' that has already been created.

--create the database
CREATE DATABASE NewDB

--create the user from the login
Use NewDB
CREATE USER [domain\user] FOR LOGIN [domain\user]

--To give user SELECT/UPDATE/INSERT/DELETE on all tables
EXEC sp_addrolemember 'db_datareader', 'domain\user'
EXEC sp_addrolemember 'db_datawriter', 'domain\user'

Alternatively to give the user admin over the database, replace the last two lines with.

--To give admin permissions
EXEC sp_addrolemember 'db_owner', 'domain\user'

CREATE DATABASE also has many options which you might need that can be found on BOL.

http://msdn.microsoft.com/en-us/library/ms176061.aspx

If you need to create a login also then you will need the following before creating the USER on your database.

--Using SQL Auth
CREATE LOGIN loginname WITH PASSWORD = 'passw0rd';

--Windows Auth
CREATE LOGIN domain\user FROM WINDOWS; 
Sign up to request clarification or add additional context in comments.

Comments

8
DECLARE
  @DatabaseName AS NVARCHAR(128),
  @Username AS NVARCHAR(128),
  @Password AS NVARCHAR(128),
  @SQL AS NVARCHAR(MAX)

SELECT
  @DatabaseName = 'YourDatabaseName',
  @Username = 'Username',
  @Password = 'Password'

SET @SQL = 'CREATE DATABASE [' + @DatabaseName + ']'
EXEC (@SQL)

SET @SQL = 'CREATE LOGIN [' + @Username + '] WITH PASSWORD = ''' + @Password + ''''
EXEC (@SQL)

SET @SQL = 'USE ' + @DatabaseName
EXEC (@SQL)

SET @SQL = 'CREATE USER [' + @Username + '] FOR LOGIN [' + @Username + ']'
EXEC (@SQL)

EXEC sp_addrolemember 'db_owner', @username

1 Comment

I used this and then logged in to new DB with new User. On selecting dropdown from ssms for this DB it says The database YourDatabaseName is not accessible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.