How to create users in databases that belong to a SQL Server Always On Availability Group

How to create users in databases that belong to a SQL Server Always On Availability Group
How to create users in databases that belong to a SQL Server Always On Availability Group

When we create new users in databases that belong to Always On Availability Group in SQL Server we want them to work even in case of failover to Secondary node, but when we create a new login in a SQL Server instance it is not automatically created on Secondary nodes. So in this article we will see how we should create logins.

How do we transfer logins to Secondary Nodes?

After creating a SQL Login on the Primary node, we run the following query on the Primary node by putting where the name of the login we created so that the DDL script that creates the login can be created for us:

SELECT N'CREATE LOGIN ['+sp.[name]+'] WITH PASSWORD=0x'+
    CONVERT(nvarchar(max), l.password_hash, 2)+N' HASHED, '+
    N'SID=0x'+CONVERT(nvarchar(max), sp.[sid], 2)+N';',
    N'ALTER LOGIN ['+sp.[name]+'] WITH PASSWORD=0x'+CONVERT(nvarchar(max), l.password_hash, 2)+N' HASHED UNLOCK ,CHECK_POLICY=OFF;'
FROM master.sys.server_principals AS sp
INNER JOIN master.sys.sql_logins AS l ON sp.[sid]=l.[sid]
WHERE sp.name = 'test';  -- Το αλλάζουμε ανάλογα με το όνομα του χρήστη που θέλουμε να μεταφέρουμε

After running it, we select the first column with the result and run the DDL on the Secondary nodes to create the login there as well:

How to create users in databases that belong to a SQL Server Always On Availability Group
01

How are rights transferred?

We do not forget that after we create the logins on all Nodes, any permissions we grant to the Primary node at the database level will automatically be transferred to the Secondary nodes, e.g. db_owner, db_datareader, db_datawriter, etc., however, permissions at the instance level, e.g. sysadmin, are not automatically transferred.

What do we do if we change the password in SQL Logins?

If we change the password of a SQL Login on the Primary node, then we run the results of the second column of the script that performs ALTER LOGIN with the new password on the Secondary Nodes.

Share it

Leave a reply