The server principal is not able to access the database under the current security context in SQL Server MS 2012

后端 未结 10 792
-上瘾入骨i
-上瘾入骨i 2020-12-13 01:46

I am trying to access my hosting server’s database through SQL Server Management Studio, everything till login is fine but when I use the command use myDatabase

相关标签:
10条回答
  • 2020-12-13 02:38

    Check to see if your user is mapped to the DB you are trying to log into.

    0 讨论(0)
  • 2020-12-13 02:39

    We had the same error deploying a report to SSRS in our PROD environment. It was found the problem could even be reproduced with a “use ” statement. The solution was to re-sync the user's GUID account reference with the database in question (i.e., using "sp_change_users_login" like you would after restoring a db). A stock (cursor driven) script to re-sync all accounts is attached:

    USE <your database>
    GO
    
    -------- Reset SQL user account guids ---------------------
    DECLARE @UserName nvarchar(255) 
    DECLARE orphanuser_cur cursor for 
          SELECT UserName = su.name 
          FROM sysusers su
          JOIN sys.server_principals sp ON sp.name = su.name
          WHERE issqluser = 1 AND
                (su.sid IS NOT NULL AND su.sid <> 0x0) AND
                suser_sname(su.sid) is null 
          ORDER BY su.name 
    
    OPEN orphanuser_cur 
    FETCH NEXT FROM orphanuser_cur INTO @UserName 
    
    WHILE (@@fetch_status = 0)
    BEGIN 
    --PRINT @UserName + ' user name being resynced' 
    exec sp_change_users_login 'Update_one', @UserName, @UserName 
    FETCH NEXT FROM orphanuser_cur INTO @UserName 
    END 
    
    CLOSE orphanuser_cur 
    DEALLOCATE orphanuser_cur
    
    0 讨论(0)
  • 2020-12-13 02:39

    This worked for me:

    use <Database>
    EXEC  sp_change_users_login @Action='update_one', @UserNamePattern='<userLogin>',@LoginName='<userLogin>';
    

    The problem can be visualized with:

    SELECT sid FROM sys.sysusers WHERE name = '<userLogin>'
    SELECT sid FROM sys.syslogins WHERE name = '<userLogin>';
    
    0 讨论(0)
  • 2020-12-13 02:39

    We had the same error even though the user was properly mapped to the login.

    After trying to delete the user it was discovered that a few SPs contained "with execute as" that user.

    The issue was solved by dropping those SPs, dropping the user, recreating the user linked to login, and recreating the SPs.

    Possibly it got in this state from restoring from backup (during a time when the related login didn't exist) or bulk schema syncing (if its possible to create an SP with execute as even though the user doesn't exist. Could also have been related to this answer.

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