2019-08-23

Disabling and Re-Enabling SQL Logins

During system maintenance, as a production DBA, you mostly need to deploy stored procedure changes and data patches on the production database. While you are apply those changes, you would like to avoid any users and applications to access the database, otherwise program errors will occur and logical data integrity will be broken. You can use below SQL script to disable non-sysadmin sql logins before you apply changes, and re-enable them after your maintenance tasks completed.
DECLARE @sysadmins table ([name] sysname);
INSERT @sysadmins SELECT prin2.[name]
FROM sys.server_principals prin
JOIN sys.server_role_members mem ON prin.principal_id = mem.role_principal_id
JOIN sys.server_principals prin2 ON prin2.principal_id = mem.member_principal_id
WHERE prin.[type] = 'R' and prin.[name] = N'sysadmin';
--SELECT * FROM @sysadmins;

DECLARE @appLogins table (id int IDENTITY, [name] sysname);
INSERT @appLogins SELECT [name] FROM sys.server_principals
    WHERE [type] = 'S' and [name] <> 'sa' AND [name] NOT IN (SELECT [name] FROM @sysadmins) AND [name] NOT LIKE '##%' AND [name] NOT LIKE '%\%';
SELECT * FROM sys.server_principals WHERE [name] IN (SELECT [name] FROM @appLogins);
DECLARE @cnt int, @loginName varchar(100);
SELECT @cnt = COUNT(*) FROM @appLogins;
WHILE @cnt <> 0
BEGIN
SELECT @LoginName = [Name] FROM @appLogins WHERE id = @cnt;
PRINT 'ALTER LOGIN [' + @LoginName + '] DISABLE;';
PRINT 'ALTER LOGIN [' + @LoginName + '] ENABLE;';
--EXEC('ALTER LOGIN [' + @LoginName + '] DISABLE;');
--EXEC('ALTER LOGIN [' + @LoginName + '] ENABLE;');
SET @cnt = @cnt - 1;
END
SELECT * FROM sys.server_principals WHERE [name] IN (SELECT [name] FROM @appLogins);

No comments:

Post a Comment