Script : Map All Orphan Users to Logins else create login and map

Script : Map All Orphan Users to Logins else create login and map

Rate This
  • Comments 2

Once of my customer asked for an "automated" script which would find all the users, which are not mapped to login and map them. Below is the logic which can be used.

<<<<<<<<<< PLEASE READ DISCLAIMER >>>>>>

If (login not exists)
create login and map login with user
else
map login with user

<Replace MYDB and Password as appropriate>

Idea taken from http://support.microsoft.com/kb/274188

Below is the script for above Logic

USE MYDB
GO
SET NOCOUNT ON
-- Declare Variables
DECLARE  @user_name  NVARCHAR(128),
         @login_name NVARCHAR(128),
         @err_msg    VARCHAR(80),
         @str        VARCHAR(250)

-- Find all users in the database MyDB which are orphan.
DECLARE FIX_LOGIN_USER INSENSITIVE CURSOR  FOR
SELECT   NAME
FROM     SYSUSERS
WHERE    ISSQLUSER = 1
         AND (SID IS NOT NULL
              AND SID <> 0x0)
         AND SUSER_SNAME(SID) IS NULL
ORDER BY NAME
OPEN FIX_LOGIN_USER

FETCH NEXT FROM FIX_LOGIN_USER
INTO @user_name
WHILE @@FETCH_STATUS = 0
  BEGIN
    SELECT @login_name = NULL
    SELECT @login_name = LOGINNAME
    FROM   MASTER.DBO.SYSLOGINS
    WHERE  LOGINNAME = @user_name
    IF (@login_name IS NULL)
      BEGIN
        SELECT @err_msg = 'matching login does not exists for ' + @user_name     
        PRINT @err_msg
        PRINT 'creating login for ' + @user_name
        SELECT @str = NULL
        SELECT @str = 'exec master.dbo.sp_addlogin ' + +'''' + @user_name + '''' + ' ,' + '''password@123''' + ' , ' + '''MyDB'''
        SELECT @str
        EXEC( @str)
        PRINT 'created and now fixing ......'
        EXEC SP_CHANGE_USERS_LOGIN
          'update_one' ,
          @user_name ,
          @user_name
        IF @@ERROR <> 0
            OR @@ROWCOUNT <> 1
          BEGIN
            SELECT @err_msg = 'error creating login for ' + @user_name
            PRINT @err_msg
          END
      END
    ELSE
      BEGIN
        PRINT ' Only fixing ......'
        EXEC SP_CHANGE_USERS_LOGIN
          'update_one' ,
          @user_name ,
          @login_name
        IF @@ERROR <> 0
            OR @@ROWCOUNT <> 1
          BEGIN
            SELECT @err_msg = 'error updating login for ' + @user_name
            PRINT @err_msg
          END
      END
    FETCH NEXT FROM FIX_LOGIN_USER
    INTO @user_name
  END
CLOSE FIX_LOGIN_USER

DEALLOCATE FIX_LOGIN_USER

GO

SET NOCOUNT OFF

--------------------------

DISCLAIMER: SCRIPT IS PROVIDED "AS IS" WITHOUT WARRANTY REPRESENTATION OR CONDITION OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO CONDITIONS OR OTHER TERMS OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. THE USER ASSUMES THE ENTIRE RISK AS TO THE ACCURACY AND THE USE OF THIS SCRIPT.

Leave a Comment
  • Please add 3 and 6 and type the answer here:
  • Post
Page 1 of 1 (2 items)