Sunday 3 November 2024

Create SQL user and grant read-only access to a database

1. Create the Login (if it doesn’t exist)
If the login for the user hasn’t been created at the SQL Server level, you need to create it. This example assumes the user is an SQL Server authentication user.

    USE [master];
    CREATE LOGIN [new_username] WITH PASSWORD = 'your_password';


2. Grant Access to the Database
Now, switch to the database you want to grant access to and create a user associated with the login.

    USE [your_database_name];
    CREATE USER [new_username] FOR LOGIN [new_username];


3. Add the User to the db_datareader Role
Finally, add the user to the db_datareader role to provide read-only access to the database.

    ALTER ROLE [db_datareader] ADD MEMBER [new_username];


No comments:

SQL Linked Server Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'

Sometimes when trying to access a linked server, you’d get an error saying “Login failed for user NT AUTHORITY\ANONYMOUS LOGON”.  This happe...