Создание и удаление пользователей в Microsoft SQL Server
Всем привет! Сейчас мы с Вами рассмотрим примеры создания и удаления пользователей в СУБД Microsoft SQL Server как с использованием инструкций Transact-SQL, так и с использованием среды Management Studio.

Процесс создания пользователей в MS SQL Server включает два этапа:
- Создание имени входа на SQL Server. Данное имя необходимо, для того чтобы предоставить пользователю возможность подключиться к экземпляру SQL Server;
- Создание пользователя базы данных. В данном случае мы уже предоставляем пользователю разрешения на объекты базы данных.
Примечание! В качестве SQL сервера у меня для примера будет выступать версия Microsoft SQL Server 2012 Express. На данном SQL сервере создана тестовая база данных Test.
Создание имени входа на MS SQL Server
Прежде чем приступать к созданию имени входа на SQL сервер необходимо определиться с методом аутентификации. Существует два варианта:
- Проверка подлинности Windows – это когда имя входа может идентифицировать пользователя как учетную запись Windows или как члена группы Windows (в том числе и доменные учетные записи, и группы);
- Проверка подлинности SQL Server. В данном случае имя входа существует только в SQL Server.
Примечание! Рекомендовано по возможности использовать проверку подлинности Windows. Проверку подлинности SQL Server можно использовать тогда, когда необходимо создать служебное или тестовое имя входа.
Давайте рассмотрим пару примеров создания имени входа на SQL сервер. Сначала мы это сделаем с помощью среды SQL Server Management Studio, а затем с использованием языка Transact-SQL.
Создание имени входа с использованием среды SQL Server Management Studio
Запускаем Management Studio, затем в обозревателе объектов находим пункт «Безопасность», раскрываем его плюсиком, кликаем правой кнопкой мыши по пункту «Имена входа» и выбираем пункт «Создать имя входа».

Далее для примера давайте создадим тестовое имя входа с проверкой подлинности SQL Server. Мы указываем имя входа, придумываем пароль и подтверждаем его. Также мы можем отметить несколько опций, например, использование политики паролей, база данных по умолчанию, язык по умолчанию и другие.

Затем нажимаем на кнопку «ОК», после чего будет создано имя входа TestLogin. По умолчанию данное имя входа будет включено, и оно будет иметь права роли сервера «public».
Создание имени входа с использованием языка Transact-SQL
Для того чтобы создать имя входа на языке Transact-SQL необходимо в Management Studio открыть редактор запросов и выполнить следующую инструкцию (она делает ровно то же самое, что и наши действия выше в графическом интерфейсе Management Studio).

Другими словами для создания имени входа в SQL сервер используется инструкция CREATE LOGIN.
Создание имени входа на SQL Server с проверкой подлинности Windows
Для того чтобы создать имя входа с проверкой подлинности Windows выполните следующую SQL инструкцию:
- ComputerName\NameUser – это Имя компьютера\Имя пользователя;
- FROM WINDOWS – указывает, что будет использоваться проверка подлинности Windows;
- WITH DEFAULT_DATABASE=[Test] – база данных по умолчанию;
- DEFAULT_LANGUAGE=[русский] – язык по умолчанию.
Отключение и включение имен входа в MS SQL Server
В случае необходимости Вы можете временно отключить имя входа, для того чтобы пользователю заблокировать доступ к серверу.
Создание пользователя базы данных в MS SQL Server
После того как имя входа создано, можно переходить к созданию пользователя базы данных, т.е. сопоставлению пользователя с именем входа.
Давайте создадим пользователя TestLogin также двумя способами, т.е. с помощью Management Studio и языка T-SQL.
Создание пользователя базы данных с помощью Management Studio
Открываем Management Studio, в обозревателе объектов находим нужную базу данных и открываем ее плюсиком. Затем также плюсиком открываем пункт «Безопасность» и кликаем по папке «Пользователи» правой кнопкой мыши и выбираем пункт «Создать пользователя».

Далее вводим имя пользователя и имя входа, которое соответствует данному пользователю (в моем случае имена совпадают), а также указываем схему по умолчанию (если не указывать, то присвоится схема dbo).

Также давайте сразу отметим роль базы данных, которую будет иметь данный пользователь. На странице «Членство» я поставил галочку напротив роли db_datareader, т.е. пользователь будет иметь права на чтение данных из пользовательских таблиц. Жмем «ОК».

Создание пользователя базы данных с помощью языка Transact-SQL
Следующая инструкция T-SQL создает пользователя базы данных (схема по умолчанию dbo) и назначает ему роль db_datareader, т.е. делает то же самое, что и мы чуть ранее в графическом интерфейсе Management Studio.
Таким образом, инструкция CREATE USER используется для создания пользователя базы данных.
Удаление пользователя базы данных и имени входа в MS SQL Server
Для того чтобы удалить пользователя базы данных можно написать простую SQL инструкцию, например
Или использовать графический инструмент Management Studio, т.е. в обозревателе объектов, в нужной базе данных выбираем «Безопасность -> Пользователи» и щелкаем правой кнопкой мыши по пользователю, которого необходимо удалить, и выбираем «Удалить».
Примечание! Пользователи, которые владеют защищаемыми объектами, не могут быть удалены из базы данных.
Для удаления имени входа можно также использовать и графический инструмент Management Studio (т.е. «Безопасность -> Имена входа» правой кнопкой мыши по имени, а затем нажать на пункт «Удалить») и инструкцию Transact-SQL т.е.
Примечание! Удалить текущее имя входа нельзя, как и имя входа, владеющее любым защищаемым объектом уровня сервера или заданием агента SQL Server. Также имя входа нельзя удалить, если в данный момент пользователь подключен к системе. Удалить имя входа без удаления сопоставленного пользователя базы данных можно, но это приведет к появлению пользователей, утративших связь с учетными записями.
Заметка! Если Вы хотите освоить язык SQL и T-SQL, рекомендую посмотреть мои видеокурсы по T-SQL.
How to Create Login, User and Grant Permissions in SQL Server

You can also create a login using the T-SQL command for SQL server create login and user.
How to Create a User in SQL Server Database
A user is an account that you can use to access the SQL server. To create user SQL server, you can use any of the following two ways:
- Using T-SQL
- Using SQL Server Management Studio
How to Create User in SQL Server Management Studio
Here is a step by step process on how to create a user in SQL Server Management Studio:
You will be creating a user for the EDU_TSQL database.
Step 1) Connect to SQL server to create new user
- Connect to SQL Server then expand the Databases folder from the Object Explorer.
- Identify the database for which you need to create the user and expand it.
- Expand its Security folder.
- Right-click the Users folder then choose “New User…”

Step 2) Enter User details
You will get the following screen,
- Enter desired User name
- Enter the Login name (created earlier)
- Click OK

Step 3) User will be created
User is created

Create User using T-SQL
You can use the T-SQL’s create user command for SQL server add user to database. The SQL create user command takes the following syntax:
Note: That the query should be executed within the query window. If a user is already created for a Login, SQL Server will throw an error if you create a user for the same login.
Assigning Permission to a User in SQL Server
Permissions refer to the rules that govern the levels of access that users have on the secured SQL Server resources. SQL Server allows you to grant, revoke and deny such permissions. There are two ways to give SQL server user permissions:
- Using T-SQL
- Using SQL Server Management Studio
Assigning Permissions in SQL Server Management Studio
Here is a step by step process on how to assign permissions to a user in SQL server management studio:
Step 1) Connect to your SQL Server instance and expand the folders from the Object Explorer as shown below. Right click on the name of the user, that is, Guru99 then choose Properties.

Step 2) In the next screen,
- Click the Securables option from the left.
- Click on Search

Step 3) In the next window,
- Select “All Objects belonging to the Schema.”
- Select Schema name as “dbo”
- Click OK

Step 4)
- Identify Table you want to Grant Permission
- In Explicit Permission select Grant
- Click Okay

Step 5) The user Guru99 is granted SELECT permission on table Course.
Grant Permissions using T-SQL
To grant permission to a user using T-SQL, you first select the database using the use statement. You then assign the permission to the user using the grant statement. Here is the syntax for SQL server create user and grant permission:
For example, the following command shows how you can grant the select permission to the user Guru99 on the object (table) named Course within the Database EDU_TSQL:
Create a New User in SQL Server
Managing SQL Server security is a critical part of maintaining your SQL Server environment. In this article, let us take a step-by-step approach to create a new database User and grant permissions to the User.
In SQL Server, a Login is created for the server instance whereas a User is created for a database. A Login has to be mapped to a User to connect to a database. A login can be mapped to only one user for any database. The scope of a User is the database
There are two ways to create a new User or to grant user permissions:
- Using Microsoft SQL Server Management Studio
- Using T-SQL
Create New User using SSMS
Open SQL Server management studio. In the Object Explorer, expand the Databases node.
Here, we are going to create a new user for the HR database. So, expand the HR database.
Expand the Security folder of the database and right click on User and select New User, as shown below.
Create a New User and Grant Permissions in SQL Server 2019
In the Database User — New dialog box, on the General tab page, User type drop down lists the following types:
- SQL user with login
- SQL user with password
- SQL user without login
- User mapped to a certificate
- User mapped to an asymmetric key
- Windows user
Select the User type as "SQL User with login" from the drop-down.
Under User name, enter a new user name. Here, we will enter ‘Steve' as a user name.
Create a New User and Grant Permissions in SQL Server 2019
Under Login name, type the previously created login i.e., Steve. Alternately click on the ellipsis . button to open the Select – Login dialog box.
Create a New User and Grant Permissions in SQL Server 2019
Click on Browse button and select an existing login name to map with this user, as shown below. Select login ‘Steve'. Click the OK button to proceed.
Create a New User and Grant Permissions in SQL Server 2019
The Owned Schema page lists all the available schemas in the database. To add schemas to the user, select the check box next to the schema name.
Create a New User and Grant Permissions in SQL Server 2019
The Membership page lists all the possible membership roles that can be owned by the database user being created. To add membership roles, select the check-box next to the roles.
Create a New User and Grant Permissions in SQL Server 2019
The Securables page lists all the securables and permissions that can be granted to the user. We will look at how to grant permissions to the User later in the article under User Permissions.
Create a New User and Grant Permissions in SQL Server 2019
The Extended Properties page allows custom properties to be added to database users.
This page displays the name of the selected database and the collation used which are read-only fields. The page also has an option to view or specify the extended properties for the object.
Create a New User
SQL Server- Create Login, User, Role and Assign Permission.
![]()
In this article, we learn how to assign permission to a SQL Server.
- Data Control Language Command restricts the user from accessing data in a database.
- GRANT command is used to provide access or privileges on the database.
- In object explorer goto Security → Right click on Logins → Select New login.
- Enter Login name
- In SQL Server authentication enter the password.
- Then click on ok.
If we refresh the Logins then we can view Login.
- In object explorer expand databases.
- Expand the database which you need to create the user.
- Expand the security folder. Right-click on Users and select New User.
- In the new pop up window enter the User name and Login name after that click on ok.
We refresh the users and then it has shown the created users.
ASSIGN PERMISSION: SQL Server allows to GRANT, REVOKE permissions.
- For assigning permission goto USER_SAMPLE property.
- Click on the search option.
- When we click on search new pop up window is open.
- Select All objects belonging to the schema
- The select schema names as “dbo” and then click on ok.
- We select the table to grant permission.
- In the Explicit permission select Grant.
- Then click on ok.
- The USER_SAMPLE is granted SELECT permission on the table Table_2.
- In the object explorer expand the databases and security folder.
- Expand Roles and right-click on Database Role.
- Click on New database role. Then a new pop up window is open.
- In the General tab enter the role name and click on ok.
Refresh the roles. In below screenshot shows the role.
- Here we drop the sample login.
- Syntax: DROP LOGIN LOGIN_NAME
If you are a newbie to database learning — SQL Server recommended is the following must-watch video: —