Ошибка 15023 sql server

Предыстория: Как-то ко мне обратились со следующим вопросом: Программа использующая в качестве СУБД 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

Error 15023: User already exists in current database.

Here two possible solutions to solve it.

1) This is the best Solution.

First of all 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.

Stored Procedure 1:

/*Following Stored Procedure will fix all the Orphan users in database
by mapping them to username already exist for user on server.
This SP is required when user has been created at server level but does
not show up as user in database.*/
CREATE PROCEDURE dbo.spDBA_FixOrphanUsers
AS
DECLARE @username VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_change_users_login 'update_one', @username, @username
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO

Stored Procedure 2:

/*Following Stored Procedure will fix all the Orphan users in database
by creating the server level user selecting same password as username.
Make sure that you change all the password once users are created*/
CREATE PROCEDURE dbo.spDBA_FixOrphanUsersPassWord
AS
DECLARE @username VARCHAR(25)
DECLARE @password VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
SET @password = @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_change_users_login 'Auto_Fix', @username, NULL, @password
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO

Stored Procedure 3:

----Following Stored Procedure will drop all the Orphan users in database.
----If you need any of those users, you can create them again.
CREATE PROCEDURE dbo.spDBA_DropOrphanUsers
AS
DECLARE @username VARCHAR(25)
DECLARE GetOrphanUsers CURSOR
FOR
SELECT UserName = name
FROM sysusers
WHERE issqluser = 1
AND (sid IS NOT NULL
AND sid <> 0x0)
AND SUSER_SNAME(sid) IS NULL
ORDER BY name
OPEN GetOrphanUsers
FETCH NEXT
FROM GetOrphanUsers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
IF @username='dbo'
EXEC sp_changedbowner 'sa'
ELSE
EXEC sp_dropuser @username
FETCH NEXT
FROM GetOrphanUsers
INTO @username
END
CLOSE GetOrphanUsers
DEALLOCATE GetOrphanUsers
GO

The SQL Server Error 15023 arises during customer arranging when you restore an informational collection to a substitute server. Support and restore are fundamental tasks in SQL Server. The essential issue is the customer arranging that may never again work when you restore the database to a substitute server.

If you try to remap the customer, you may end up with a slip-up. Around here at ARZHOST, we have seen a couple of establishments for this misstep while exploring SQL issues as an element. “Microsoft SQL Server Error 15023” our Server Management Services for the web has and online expert communities.

Today at arzhost.com, we’ll explore the justification behind this screw-up and how to fix it.

More concerning SQL Server Error 15023

In SQL Server, support and restore are clear tasks. The fundamental issue that arises here is that customer arranging doesn’t work when you restore the informational collection to a substitute server. “Microsoft SQL Server Error 15023” Expecting you endeavor to design informational collection to a customer by going to

  • Security >> Logins >> right snap some customer >> Properties >> User Mapping >> Select DB >> set as db_owner and a short time later okay, the going with error is gotten as shown in picture:

What causes SQL Server Error 15023 to occur?

Regularly, when we support and restore informational indexes across the SQL servers. “Microsoft SQL Server Error 15023” we are simply restoring a customer informational collection and not the master informational collection where logins are kept.

Ensuing to restoring we guess that the restored informational index should work much the same way as the support. Notwithstanding, the login miss the mark for a customer that had approvals in the maintained up the database. This issue is caused because of Security recognizing confirmation numbers (SID) that are muddled or ‘abandoned’ in the sysusers table.

How do we fix SQL Server Error 15023?

Lately, one of our customers pushed toward us with a comparable error message. By and by, we ought to see how our Hosting Expert Planners settle this slip-up.

1) Initially, we ran the going with T-SQL Query in Query Analyzer. This will return all of the current customers in the database in result skillet:

  • USE Your DB
  • GO
  • Leader sp_change_users_login 'Report'
  • GO

To relate login with the username, we ran the going with T-SQL Query in Query Analyzer. Here, the ‘Auto Fix’ property will make the customer in SQL Server case in case it doesn’t exist.

In like manner, in the inquiry, we invigorated the ‘Username’ with genuine customer username and ‘Secret expression’ with certified Password. “Microsoft SQL Server Error 15023” Auto-Fix interfaces a customer section in the sysusers table in the current informational collection to a login of a comparative name in sysxlogins.

  • USE Your DB
  • GO
  • Leader sp_change_users_login 'Auto Fix', 'Username', NULL, 'Secret word'
  • GO

To relate login with the username, we ran the going with T-SQL Query in Query Analyzer. Here, ‘Update One’ will connect the foreordained customer in the current database to log in. Here, login ought to at this point exist, customer and login ought not to be set in stone and mystery expression should be NULL or not shown.

  • USE Your DB
  • GO
  • Leader sp_change_users_login 'update one', 'ColdFusion', 'ColdFusion'
  • GO

2) We ran the going with T-SQL in Query Analyzer since the login account had agreed to drop various customers. This inquiry will drop the customer:

  • USE Your DB
  • GO
  • Chief sp_dropuser 'ColdFusion'
  • GO

Then, “Microsoft SQL Server Error 15023” we made a comparative customer again in the database with no error.

Termination

Along these lines, “Microsoft SQL Server Error 15023” This SQL error can arise during customer arranging when you restore a database to a substitute server. Today at arzhost.com, we saw the objective to this SQL screw-up.

In this post i will discuss about Error 15023 User already exists in the current database in SQL Server which can occur between SQL Server Login and Database User, This problem is also called Mismatched SID Problem

When an SQL Server login is created, the login is allocated both a name and a Security ID (SID).When a database user is created for the login, details of the SID for the login are entered into the database.

If the database is then backed up and restored onto second server, then database user still has the entry of SID of the previous server.When you create new Login on the second server it will have different SID. It means that SID of Database User is different from SID of Login. This is called Mismatched SID problem.

This is solved by two methods

1) Change the SID of the database user by the SID of the newly created Login created on the second server.This can be done via the ALTER USER command

2) Create the new login with the SID of the existing Database User

Demonstration

Now I am restoring a backup of a database which contains a user for a non-existent login. The name of my sample database is Mismatch database.

I right click on the database and then click Restore Database.

User already exists in the current database - Mismatched SID Problem

Choose the option from device then click the ellipses button and choose the path where the backup file is placed and hit Ok two times to restore the backup as shown below.

User already exists in the current database - Mismatched SID Problem

Now i create a login TestUser as shown below.

User already exists in the current database - Mismatched SID Problem

Try to create a user in the database for the login.
Note that this command fails also as a user with that name already exists.

User already exists in the current database - Mismatched SID Problem

Now question arises why did i create Login Name as  “TestUser” and Database User name as “TestUser”.This is because my sample database named Mismatch had Login Name        ” TestUser” as well as Database User name as “TestUser” in the first server.

From the command below i can view the database user present in the database
There is a TestUser already exists in the current database. Before running the sys.database_principals make sure Mismatch database must be selected as shown in the image below with highlighted red box.

User already exists in the current database - Mismatched SID Problem

Query the security IDs at both the server level and the database level to see the problem.The figure below shows that the security ID or SID of Login doesn’t match with the User of the database.

User already exists in the current database - Mismatched SID Problem

To map User of the database with the Login of the SQL Server is to correct the sid in the database. This can be done via the ALTER USER command as shown below.

User already exists in the current database - Mismatched SID Problem

Now i query the security IDs at both the server level and
the database level to see the outcome.

Note that the sids have been set to the value from the login, not the value from the database as shown below.

User already exists in the current database - Mismatched SID Problem

There is another option also available where you can set the value of the database SID to the Login.This can be done by creating the Login with the SID of the Database User as shown below.

User already exists in the current database - Mismatched SID Problem

Browse All Articles > SQL Server: «Error ‘15023’ User or role already exists in the current database» when you perform restore database from backup

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into «Error ‘15023’ User or role already exists in the current database» when you use the «User Mapping» SQL Management Studio functionality to allow necessary user permissions to the new database. This is puzzling enough since a database backup should bring us back to the original state. This is caused by Security Identification numbers (SID) that are mismatched or ‘orphaned’ in the sysusers table.

To resolve this problem, we can make use of the SQL Server stored procedure
sp_change_users_login.

From MSDN, the syntax of
sp_change_users_login is:

sp_change_users_login [ @Action= ] ‘action’

    [ , [ @UserNamePattern= ] ‘user’ ]

    [ , [ @LoginName= ] ‘login’ ]

    [ , [ @Password= ] ‘password’ ]

[;]

1. Switch to the target database

use mydatabasename
                      

Open in new window

2. List problematic SID

Lists the users and corresponding security identifiers (SID) in the current database that are not linked to any login. user, login, and password must be NULL or not specified. This step is informative and thus
optional.

exec sp_change_users_login @Action='Report'
                      

Open in new window

3. Fix problematic SID

Links the specified user in the current database to an existing SQL Server login. User and login must be specified. password must be NULL or not specified. The login name(s) to provide is/are from the result reported in step 2.

exec sp_change_users_login @Action='Update_One', @UserNamePattern='MyLoginID', @LoginName='MyLoginID'
                      

Open in new window

Repeat running ‘Update_One’ statement for all login names.

4. Verify all is okay now

Repeat the sql statement with Action=’Report’ as described in step 2 to confirm we have resolved all login names. If no records are returned after running Action=’Report’, we are 99% there!

Now, try logging in using the «just-fixed» SQL user login id to confirm we have resolved «Error ‘15023’».

TIP: You may wish to save the your sql statements into a .sql file so you can reuse it in future database migration/restore.

MSDN Reference:
http://msdn.microsoft.com/en-us/library/ms174378.aspx

To view the original article and discussion you can visit my blog
here.

Cheers

hongjun

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка 150200 мерседес w166
  • Ошибка 1513 ваз 2110
  • Ошибка 15125 ауди
  • Ошибка 1502 тарков

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии