Microsoft sql server ошибка 15023

Предыстория: Как-то ко мне обратились со следующим вопросом: Программа использующая в качестве СУБД MS SQL Server не видит одну из баз, причем в Management Studio база видна и данные в ней есть.

Попытка просто расставить необходимые права к ожидаемому результату не привела — при попытке установить права возникла ошибка:

Create failed for User ‘*’. (Microsoft.SqlServer.Smo)
User, group, or role ‘*’ already exists in the current database. (Microsoft SQL Server, Error: 15023)

Копание в интернет привело к следующим рекомендациям:

Чтобы исправить данную ошибку, есть два различных способа в зависимости от версии SQL Server, который вы используете. Обе эти команды производят ремап (пере-ассоциацию) пользовательского идентификатора безопасности (SID), чтобы привести его в соответствие с SID в логине SQL Server’а.

Для SQL Server 2008 / SQL Server 2008 R2 / SQL Server 2012

ALTER USER user WITH LOGIN = serverlogin 

где имя проблемного serverlogin пользователя, а имя user пользователя в самой базе (подробнее по ссылке https://msdn.microsoft.com/ru-ru/library/ms176060.aspx)

Для более старых SQL Server 2005 / SQL Server 2000

EXEC sp_change_users_login ‘Auto_Fix’, ‘user’

вся магия использования по прежнему по ссылке https://msdn.microsoft.com/ru-ru/library/ms174378.aspx

Но, как это и бывает в основной массе случаев, данный рецепт мне не помог.

Решение оказалось достаточно банальным:

Итак, по шагам:

  1. Открываем интересующую нас базу в Microsoft SQL Server Management Studio
  2. Идем в раздел Security -> Users. Там открываем интересующего нас пользователя
  3. Открываем вкладку General
  4. В разделе Database role membership выбираем необходимые нам права (мне хватило бы db_datawriter и db_datareader)

На этом все! База подключается, данные пишутся-читаются.

Разбор полетов: Было очень важно узнать как же данный инцидент мог произойти дабы исключить его в дальнейшем. Расследование показало достаточно обидный промах — база была восстановлена из резервной копии пользователем sa, что в конечном итоге привело к смене db_owner, а права на чтение и запись у нашего пострадавшего пользователя не были установлены (до переноса базы он успешно работал с ней как владелец).

Выводы (не претендующие на объективность):

  1. Всегда необходимо проверять не только возможность авторизации пользователя, но и наборы его прав на интересующую нас базу.
  2. Восстановление (перенос на новый сервер) лучше осуществлять под тем пользователем, который будет с данной базой работать в дальнейшем.
  3. В случае ошибки подключения пользователя с базе или сообщения, что базы не существует — можно выдать данному пользователю права System Administrator для проверки возможности подключения и уверования в неправильно выставленные права. Работать из-вне с правами System Administrator крайне не желательно.

if it is just one or two users, then easiest way is to drop the database user from the restored database, remap the database user to the server login using SSMS. If the server login does not exist then just create it, map the user.

Option 2: If you are migrating a large number of users, use sp_help_revlogin. sp_help_revlogin is a Microsoft supplied stored procedure that will help migrate logins from one server to another, including passwords and SIDs. Here is a good article about it SP_HELP_REVLOGIN : http://www.databasejournal.com/features/mssql/article.php/2228611/Migrating-Logins-from-One-SQL-Server-to-Another.htm

Code patches to help use it :
run following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.

USE YourDB
GO
EXEC sp_change_users_login 'Report'
GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist. In following example ‘ColdFusion’ is UserName, ‘cf’ is Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.

USE YourDB
GO
EXEC sp_change_users_login 'Auto_Fix', 'ColdFusion', NULL, 'cf'
GO

Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Update_One’ links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified

USE YourDB
GO
EXEC sp_change_users_login 'update_one', 'ColdFusion', 'ColdFusion'
GO

2) If login account has permission to drop other users, run following T-SQL in Query Analyzer. This will drop the user.

USE YourDB
GO
EXEC sp_dropuser 'ColdFusion'
GO

Create the same user again in the database without any error.

  • Remove From My Forums
  • Question

  • Any idea how to solve this?

    I tried to rename User Mapping from ‘sa’ to ‘dbo’ but failed with above error….

    Thanks

Answers

  • As stated above — the sa login already has db_owner privileges on all databases.

    If you try to create a user sa in a database this is the T-SQL that is executed in the background:

    USE [database]

    GO
    CREATE USER [sa] FOR LOGIN [sa] WITH DEFAULT_SCHEMA=[dbo]
    GO

    This statement will fail.

    If the sa account has already been mapped to a database as the dbo user (the default database owner) the an attempt to change that to sa will result in this code behind the scenes:

    USE [database]
    GO
    ALTER USER [dbo] WITH NAME=[sa]
    GO

    This statement will also fail.

    If you want to map the sa account into explicit databases then use the dbo user…


    Regards, Matt Bowler MCITP,
    My blog | SQL Services

    • Proposed as answer by

      Wednesday, December 19, 2012 1:49 AM

    • Marked as answer by
      rontol
      Wednesday, December 19, 2012 2:34 AM

  • I’ll marking detailed explanation as indirect answer, issue actually related to the application installer did not recognize SQL server hostname.

    We used server IP instead.

    Thanks again.

    • Marked as answer by
      Kalman Toth
      Wednesday, December 19, 2012 3:02 AM

The SQL Server Error 15023 arises during user mapping when you restore a database to a different server.

Here at Bobcares, we have seen several causes for this error while troubleshooting SQL issues as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the cause for this error and how to fix it.

More about SQL Server Error 15023

In SQL Server, backup and restore are simple tasks. The only problem that arises here is the user mapping don’t work when you restore the database to a different server. If you try to map database to a user by going to

Security >> Logins >> right click some user >> Properties >> User Mapping >> Select DB >> set as db_owner and then ok, the following error is received as shown in image:

SQL Server Error 15023

What causes SQL Server Error 15023 to occur

Normally, when we backup and restore databases across the SQL servers, we are only restoring a user database and not the master database where logins are kept.

After restoring we expect the restored database to work in the same way as the backup. But the login fails for a user that had permissions in the backed up database. This issue caused due to Security identification numbers (SID) that are mismatched or ‘orphaned’ in the sysusers table.

How we fix SQL Server Error 15023

Recently, one of our customers approached us with the same error message. Now, let’s see how our Support Engineers resolve this error.

1) Initially, we ran the following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.

USE YourDB
GO
EXEC sp_change_users_login ‘Report’
GO

To associate login with the username, we ran the following T-SQL Query in Query Analyzer. Here, ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist.

Also, in the query we updated the ‘Username’ with actual customer username and ‘Password’ with actual Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.

USE YourDB
GO
EXEC sp_change_users_login ‘Auto_Fix’, ‘Username’, NULL, ‘Password’
GO

To associate login with the username, we ran the following T-SQL Query in Query Analyzer. Here, ‘Update_One’ will link the specified user in the current database to login. Here, login must already exist, user and login must be specified and password must be NULL or not specified.

USE YourDB
GO
EXEC sp_change_users_login ‘update_one’, ‘ColdFusion’, ‘ColdFusion’
GO

2) We ran the following T-SQL in Query Analyzer since the login account had permission to drop other users. This query will drop the user.

USE YourDB
GO
EXEC sp_dropuser ‘ColdFusion’
GO

Then we created the same user again in the database without any error.

[Need any further assistance in fixing SQL errors? – We’re available 24*7]

Conclusion

In short, This SQL error can arise during user mapping when you restore a database to a different server. Today, we saw the resolution to this SQL error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

  • Remove From My Forums
  • Вопрос

  • I have three different environments in my database: DEV=Development, TRAIN=Training and PROD=Production, When I copy PROD onto TRAIN or DEV I do it by creating a Backup of PROD then restoring it onto TRAIN and DEV. Then I change the Login Properties User mapping. this works fine for the TRAIN environment, but for DEV when I try to check the ‘master’ dbo as public, I get back Error 15023. I tried droping the owner and setting again, but no luck. any suggestions?

Ответы

  • You are receiving 15023 error as you are restoring a MS SQL database from a backup. Keep in mind that when you perform backup and restore across the sql servers you are only restoring a user database and not the master database where logins are kept.

    You expect a restored database to be in exactly the same state as the backup, but the login fails for a user that had permissions in the backed up database.   This is caused by Security identification numbers (SID) that are mismatched or ‘orphaned’ in the sysusers table. 

    a)

    Use [YourDatabase]
    Go

    this will report all the orphaned login
    EXEC sp_change_users_login @action=’Report’;

    this should fix a orphaned user
    Exec sp_change_users_login @action=’Update_One’, @UserNamePattern= [orphaneduserDBUserName] , @LoginName=[orphaneduserloginname]

    b) or you can search for a script that can do this for all the orphaned users

    • Помечено в качестве ответа

      30 сентября 2009 г. 10:23

  • Hi,

    Explain the below mention points to understand the issue.

    PROD-
    MSSQL Server version
    MSSQL Server SP

    Dev
    MSSQL Server version
    MSSQL Server SP

    Login Property 

    Windows Login
    SQL login.

    Microsoft reported as BUG for sql 2000 behaviour, Try it..
    http://support.microsoft.com/kb/819261
    User logons and permissions on a database may be incorrect after the database is restored
    http://support.microsoft.com/kb/168001

    BR
    Praveen Barath

    -Mark as ANSWER if helps-

    • Помечено в качестве ответа
      Xiao-Min Tan – MSFT
      30 сентября 2009 г. 10:25

Понравилась статья? Поделить с друзьями:
  • Microsoft visual basic ошибка 1004
  • Microsoft sql server ошибка 1418
  • Microsoft sql server ошибка 1225
  • Microsoft sql server ошибка 1222
  • Microsoft sql server management studio ошибка 18456