How do you use the CREATE LOGIN statement to create a new SQL Server login?
Posted by BobHarris
Last Updated: June 16, 2024
In SQL Server, you can create a new login using the CREATE LOGIN statement. This statement allows you to create a login that can authenticate users to the SQL Server instance. Here’s the basic syntax and an example of how to use it:
Basic Syntax
CREATE LOGIN login_name
WITH PASSWORD = 'strong_password';
Parameters
- login_name: The name you want to give to the new login. It should be unique within the SQL Server instance. - PASSWORD: The password for the new login. This must meet the password complexity requirements set in the SQL Server instance.
Example
Here’s an example of creating a new SQL Server login:
CREATE LOGIN MyNewLogin
WITH PASSWORD = 'P@ssw0rd123!';
Additional Options
You can also specify additional options when creating a login: 1. Default Database: Set a default database for the login. 2. Check Expiration: Determine if the password should expire. 3. Check Policy: Enable or disable password policy enforcement.
Example with Options
CREATE LOGIN MyNewLogin
WITH PASSWORD = 'P@ssw0rd123!',
     DEFAULT_DATABASE = MyDatabase,
     CHECK_EXPIRATION = ON,
     CHECK_POLICY = ON;
Important Notes
- Always adhere to security best practices when setting passwords. - Ensure that the password meets the complexity requirements of your SQL Server configuration. - After creating a login, you may need to assign it to a specific database and give it appropriate permissions using the CREATE USER statement in conjunction with GRANT or ALTER ROLE.
Example of Creating User and Assigning Role
After creating a login, you would typically create a user for that login in a specific database:
USE MyDatabase;
CREATE USER MyNewUser FOR LOGIN MyNewLogin;
ALTER ROLE db_datareader ADD MEMBER MyNewUser;
ALTER ROLE db_datawriter ADD MEMBER MyNewUser;
By following these instructions, you'll be able to create a new SQL Server login effectively while adhering to best practices related to security and permissions.