SQL map a login to an existing user

前端 未结 3 1747
半阙折子戏
半阙折子戏 2021-02-18 22:10

I have recently upgraded my development environment from SQL 2000 to SQL 2008 R2. I\'ve done a backup of our production db and restored it our new dev server.

I have cr

相关标签:
3条回答
  • 2021-02-18 22:42

    Under SQL Server 2012, the user 'dbo' cannot be altered.

    0 讨论(0)
  • 2021-02-18 22:53

    I think Nikola Markovinović's comment to this post needs to be added as an answer. Use the Alter user command:

    USE {database}; 
    ALTER USER {user} WITH login = {login}
    

    Where:

    • {database}: The database containing the orphan user
    • {user}: The orphan user name
    • {login}: The login name. You can use the same login as used on the old server or map the user to a different login name

    I found this answer at http://www.aip.im/2010/05/re-map-database-user-to-login-in-sql-server-after-restoring-or-attaching-database/#sthash.fbazv94Z.dpuf

    0 讨论(0)
  • 2021-02-18 22:54

    To reconcile the the user with the login, you can used the system stored procedure sp_change_users_login.

    sp_change_users_login [ @Action = ] 'action'
    [ , [ @UserNamePattern = ] 'user' ] 
    [ , [ @LoginName = ] 'login' ] 
    [ , [ @Password = ] 'password' ];
    

    For example:

    EXEC sp_change_users_login 'Update_One','User123','User123'

    If you have a lot of users who are out of sync, you can use a cursor to pull out all of the users and run this command for them. There isn't any adverse effect to running this against users that aren't out of sync, and it will fix all of the orphaned users.

    DECLARE @sql NVARCHAR(MAX);
    DECLARE curSQL CURSOR
    FOR
           SELECT   'EXEC sp_change_users_login ''UPDATE_ONE'', ''' + name + ''', ''' + name + ''''
           FROM     sysusers
           WHERE    issqluser = 1
                    AND name NOT IN ( 'guest', 'dbo', 'sys', 'INFORMATION_SCHEMA' )
    OPEN curSQL
    FETCH curSQL INTO @sql
    WHILE @@FETCH_STATUS = 0 
         BEGIN
               EXEC (
               @sql
               )
               FETCH curSQL INTO @sql
         END
    CLOSE curSQL
    DEALLOCATE curSQL
    

    This has to be run of the context of the database you need the users fixed in.

    0 讨论(0)
提交回复
热议问题