11

On a SQL Server 2014 instance with enough RAM and fast disks, there are over 160 users that have access to a database. For some reason unbeknownst to me, running the command DROP USER [username] in this database takes up to 5 seconds per user.

Remapping users to logins and restoring their permissions is very fast.

Within the context of refreshing DEV databases from production, I have to drop and recreate all database users. So yes dropping the database users and recreating them is necessary.

How do I speed up the DROP USER command?

Remember, I have to run it over 160 times for the instance I'm writing about.

This is the SQL I'm using:

DECLARE drop_user_cur CURSOR FOR 
SELECT name FROM #drop_users

OPEN drop_user_cur
FETCH NEXT FROM drop_user_cur INTO @user

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'use [' + @db_name + '] DROP USER [' + @user + ']'
    BEGIN TRY
        print @sql
        EXECUTE(@sql)
    END TRY
    BEGIN CATCH
        print 'ERREUR : ' + @sql
    END CATCH
    FETCH NEXT FROM drop_user_cur INTO @user
END

CLOSE drop_user_cur
DEALLOCATE drop_user_cur

The problem is not coming from cursor; it's the actual DROP USER that's taking up to 5 seconds.

Using sp_whoisactive, the wait_type is NULL.

enter image description here

Don't pay attention to the duration, the DROP and CREATE USER were being run in a WHILE loop which is why it's saying more than a minute.

Profiler shows over 125,000 reads to execute DROP USER.

Service Broker is not enabled.

  • 1
    @CraigEfrein You can undelete your answer. Looks good and thanks for including my comment in your answer. I am happy that you found the solution working ! – Kin Shah Jun 6 '16 at 13:31
6

The resolution to this issue was enabling service broker on the database as so.

ALTER DATABASE [Database_name] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

After enabling service broker for the database, drop users were practically instantaneous.

Kin asked if the service broker was enabled in a previous comment which sent me searching in the right direction.

2

this is not an answer to the question but an argument to dismiss it altogether.

If I understand correctly your comment:

Within the context of refreshing DEV databases from production, I have to drop and recreate all database users. So yes dropping the database users and recreating them is necessary.

your goal is to copy production data onto a dev system and have it working with the same permission as the production one, using the same user names.

The quickest path is to clone sql logins from the production system onto the dev system using the procedure described by ms in this kb article.

with the procedure defined by ms the result is that you can restore the databases on your dev server and the permission are working without changes.

I successfully used the above mentioned procedure to copy a sql 2005 production env onto both test & dev sql 2012 environments.
After cloning the users, a simple database restore led me to a pair of fully working new systems with up to date data.

The huge plus of that solution is that to refresh dev data you just restore the production database and that's it; you will have to adjust references, synonyms and such but permissions will not be broken.

Here is the code from the article, just for reference, but please refer to the article that has remarks and details about compatibility with ancient sql versions, password encryption details and other information that may save you some headache while transferring the logins across servers:

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO

IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname

IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT

        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name

            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO
  • 1
    Hello there. I am not trying to create an exact copy of users from production. The DEV is not really an exact copy of production. The logins don't use the same password and dev is not within the same domain. There are other constraints that make deleting database users necessary which I won't bore you with. – Craig Efrein Jun 1 '16 at 12:38
  • Acutally on the security side, you should NEVER have passwords from production touch your development environment. You just provided your developers access to production doingi that, and hope none of them have security admin role. – Shawn Melton Jun 1 '16 at 13:54
  • if users have passwords then you are dealing with sql users so the domain is not relevant. also the passwords are not locked so you can change them as soon as the users are created. the script can be altered before running it: remove all unwanted/unneeded users and you should be ok. my suggestion is not the solution for your issue but maybe after cloning you will need to drop fewer users because permission are not to be handled anymore. not optimal but maybe an improvement ^^ – Paolo Jun 1 '16 at 14:57
0

A cursor similar to this should work

Use DB_name

declare @username varchar(50)
declare user_cursor cursor for select '['+name+']' from sys.database_principals where type in ('u', 's') and principal_id>4
open user_cursor
fetch next from user_cursor into @username
while (@@fetch_status=0)
begin
EXEC sp_dropuser @username
fetch next from user_cursor into @username
end
close user_cursor
deallocate user_cursor
go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.