Avatar of marrowyung
marrowyung

asked on 

when sp_change_users_login command execute one by one

Hi all,

when  I am fixing  orphan users after restoring production DB to test server, I need to run the sp_change_users_login SP, but I think when I try to automate that by this script:

DECLARE @Username VARCHAR(100),
        @cmd      VARCHAR(100)

DECLARE userlogin_cursor CURSOR FAST_FORWARD FOR
  SELECT username = name
  FROM   sysusers
  WHERE  issqluser = 1
     AND (sid IS NOT NULL
          AND sid <> 0x01)
     AND Suser_sname(sid) IS NULL -- AND name='jtang'
  ORDER  BY name
  FOR READ ONLY

OPEN userlogin_cursor
FETCH NEXT FROM userlogin_cursor INTO @Username

WHILE @@FETCH_STATUS = 0
  BEGIN

/* debug */
 -- SET @cmd = 'select  ''sp_change_users_login "update_one", "' + @username + '", "' + @username + '" '' '
    SET @cmd = 'sp_change_users_login "update_one", "' + @username + '", "' + @username + '"'
      EXECUTE(@cmd)
	  PRINT(@cmd)
      FETCH NEXT FROM userlogin_cursor INTO @Username
  END

CLOSE userlogin_cursor
DEALLOCATE userlogin_cursor

Open in new window


it will generate the following command:

sp_change_users_login "update_one", "AdminProxy", "AdminProxy" 
sp_change_users_login "update_one", "CybernetUser", "CybernetUser" 

Open in new window


but I find I can only execute them one by one instead of all together, any reason for that ?
Microsoft SQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
marrowyung

8/22/2022 - Mon