Sql ошибка 15025

imageВо время миграции баз данных SQL Server 2012 из ранее используемого кластерного экземпляра SQL Server на физических серверах в новый кластерный экземпляр в виртуальной среде Hyper-V столкнулся с одной интересной проблемой. Сразу скажу, что она никак не связана ни с Hyper-V, ни с виртуализацией в целом, а скорее с простым незнанием некоторых аспектов работы SQL Server.

При копировании баз данных была предпринята попытка использования мастера копирования баз (Copy Database Wizard), который доступен нам в составе SQL Server Management Studio по аналогии с ранее описанной процедурой. Процедура копирования контентной базы данных одного из веб-приложений SharePoint и связанных с ней SQL-логинов была прервана с ошибкой, говорящей о том, что один из SQL-логинов невозможно найти в домене. Выяснилось, что этот SQL-логин когда-то ранее было создан на SQL Server с привязкой к существующей на тот момент доменной учетной записи пользователя, однако на текущий момент учётной записи с таким именем в домене действительно нет. Это подтвердил также и вывод хранимой процедуры sp_validatelogins, которая умеет обнаруживать “осиротевшие” SQL-логины:

EXEC sp_validatelogins; 
GO

image

В нашем примере проблемный SQL-логин имел имя KOM\s-KOM-SP-ORD. Соответственно этому SQL-логину ранее и были права необходимые для работы с контентной базой данных веб-приложения SharePoint, но вместе с этим само веб-приложение в SharePoint на текущий момент времени работало от имени совершенно другой учетной записи – KOM\s-KOM-SP-IRS. Это ввело меня в некоторый ступор. Как такое вообще возможно… И пока до меня не “дошло”, в чём же на самом деле заключается проблема, выполнялись разного рода манипуляции. Например, будучи уверенным в том, что учетной записи веб-приложения таки нужен доступ к его контентной базе данных SharePoint, я попытался добавить в SQL Server новый SQL-логин — KOM\s-KOM-SP-IRS. Но в ответ получил странное сообщение о том, что такой логин в SQL Server уже присутствует… 

Create failed for Login 'XXX\XXX'.  (Microsoft.SqlServer.Smo)
...
The server principal 'XXX\XXX' already exists. (Microsoft SQL Server, Error: 15025)

image

Но как? Ведь я не вижу этого логина в консоли…

И тут меня осенило, что скорее всего, нынешняя доменная учетная запись KOM\s-KOM-SP-IRS это и есть учётная запись KOM\s-KOM-SP-ORD, просто переименованная в домене после того, как в SQL Server был создан сопряжённый с ней SQL-логин. Чтобы проверить это предположение, нужно было выяснить доменный идентификатор безопасности (SID) хранимый в SQL Server для SQL-логина KOM\s-KOM-SP-ORD и сравнить его с SID пользователя KOM\s-KOM-SP-IRS в домене на данный момент. Новой сложностью стало то, что SQL Server возвращает значение SID в формате VARBINARY(85), а в домене оно хранится в другом формате.

Выполнить преобразование полученного из SQL Server значения SID в формат аналогичный атрибуту objectSid для учетных записей в домене Active Directory помог SQL-скрипт из статьи Help: SQL Server — SQL Internals — How to map login SID to domain account?, за что её автору большое спасибо…

DECLARE @varBinarySID VARBINARY(85)
-- в переменной varBinarySID указываем значение SID в формате varbinary(85)
SELECT @varBinarySID = 0x010500000000000515000000685889B0E3259CD7E0ED9A5545030300
DECLARE @StringSID VARCHAR(100)
DECLARE @len AS INT
SET @len = LEN(@varBinarySID)
DECLARE @loop AS INT
SELECT @StringSID = 'S-'
SELECT @StringSID = @StringSID + CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@varBinarySID, 1, 1))))
SELECT @StringSID = @StringSID + '-'
SELECT @StringSID = @StringSID + CONVERT(VARCHAR, CONVERT(INT, CONVERT(VARBINARY, SUBSTRING(@varBinarySID, 3, 6))))
SET @loop = 9
WHILE @loop < @len
BEGIN
    DECLARE @temp_var BINARY (4)
    SELECT @temp_var = SUBSTRING(@varBinarySID, @loop, 4)
    SELECT @StringSID = @StringSID + '-' + CONVERT(VARCHAR, CONVERT(BIGINT, CONVERT(VARBINARY, REVERSE(CONVERT(VARBINARY, @temp_var)))))
    SET @loop = @loop + 4
END
SELECT @StringSID 'String SID'

image

Итак, значение objectSid в более привычном формате получено  и теперь всё что остаётся сделать, это сравнить это значение с учетной записью KOM\s-KOM-SP-IRS. Методов для этого много разных, как один из самых простых и быстрых воспользоваться обратным преобразованием SID в имя с помощью утилиты Марка Руссиновича — Psgetsid

image

Получается, что действительно, SQL-логин KOM\s-KOM-SP-ORD имеет привязку к доменному SID учетной записи KOM\s-KOM-SP-IRS. Как я уже и сказал, такая ситуация возможна в случае если в домене учетная запись была переименована после создания соответствующего логина в SQL Server. Теперь, чтобы окончательно поставить всё на свои места осталось только переименовать SQL-логин в актуальное для доменной учетной записи имя.

  • Hi Muhammed,

    Please go through the below steps,

    
    
    use master 
    go
    drop login <yourloginname>
    go
    create login <yourloginname> with password='yourpassword',<requiredoptions>
    go

    for the various option available with create login pls refer :

    http://msdn.microsoft.com/en-us/library/ms189751.aspx

    If the login is already there, you can try to fix the orphan users in DB instead of deleting the login.

     you can use

    alter user username with login=loginname

    please refer alter user syntax here

    http://msdn.microsoft.com/en-us/library/ms176060.aspx

    or

    You can make use of  sp_change_users_login which is deprecated to fix the orphan user issue after restoring Db from one server to another server.

    After fixing the orphan users issue your login in the new server will be able to connect to the restored DB with all the permissions as in the old server.

    But if you have already deleted the users in the DB, then you have to create the user for the login.

    Thanks

    • Edited by

      Tuesday, June 18, 2013 8:47 AM

    • Marked as answer by
      Fanny Liu
      Saturday, June 22, 2013 9:38 AM

    • Question

    • Hi guys, my colleague deleted by mistake a user. Now I tried to create the login again but it did say the login is already in the server. I deleted the login from each database it was linked but the error The server principal NetworkName\UserName already
      exist. The user can connect a linked server which I granted for him. Quite strange.

      Why I can’t add the user again. What can I do?

    All replies

    • Your college probably deleted a database user and not a login. It does not sound like he actually deleted a login as QSL Serer things it already exists.

      What problem is this causing for you?

    • Update. I refreshed and the user did appear again but only for one db it’s happen this strange behavior. I set the user as db reader, I click ok, I close the mask and when I open the mask again the db reader is unticked. Any idea why?

    • What does this query show?

      select u.name,r.name from sys.database_principals u
      join sys.database_role_members dp on dp.member_principal_id=u.principal_id
      join sys.database_principals r on r.type='R' and dp.role_principal_id=r.principal_id
      where u.name='DatabaseUserName'
      

    • And if you try this:

      exec sp_addrolemember 'db_datareader', 'MyDatabaseUser'  

      And then run the query?

      Are there any database triggers on this database?

    • It says Command completely successfully but if I see the database in the user mask is still unticked. No triggers.

    • Does the user now show up in here?

      select u.name,r.name from sys.database_principals u
      join sys.database_role_members dp on dp.member_principal_id=u.principal_id
      join sys.database_principals r on r.type='R' and dp.role_principal_id=r.principal_id
      where u.name='DatabaseUserName'
      

      If the user in the db_owner role as well?

    • Nothing. It doesn’t show up.

    • I guess something wrong in the db.

    • sometimes the error 15025 resolved by removing windows account which is still in the sql server account list. please take a look on here if it is helpful for you:
      https://blogs.msdn.microsoft.com/sqlserverfaq/2010/04/06/unable-to-create-a-login-in-sql-server-2005-and-we-get-the-following-error-the-server-principal-domainmachine-account-already-exists/

    It’s friday and it’s dark and drizzling outside which usually makes me lazy..,:) But I got this one ticket from one of our customers requesting to create a Login which made me active :D.  Well, thought creating a login is just a basic routine security request, Went ahead and tried creating the login from SSMS. It failed…saying “The server principal already exists”1

    Well, I thought the login already exists and verified from SSMS( I didn’t found one…Hmmm Interesting). Assuming might be a bug in SSMS, i tired using T-SQL, same message again…as you can see below.

    2

    Basically, I am not seeing the login(Server Principal) but SQL Server says it already has one!!!…To double check I queried sys.server_principals and also used sp_helprevlogin to see if it can show something useful to me.  But I had no luck again as you can see below…they are not giving me any useful results when I am querying using Login Name.

    3

    Now..It’s time to play with SIDs(SUSER_SID is super useful in this scenario). I queried SUSER_SID passing the login name which I am trying to create, Interestingly it returned a row as you can see below…

    4

    Right away I queried sys.server_principals again, but with SID(Use the SID which came from the above query) this time as opposed to Login Name. Results are shown below

    5

    Tadaaaaa…..There you go! It returned a different login name which already exsits on the SQL Server with the same SID of the new login which I’m trying to create. 

    So, I contacted customer saying ‘ Hey, Login A is conflicting with your login, do you happen to know what Login A is?’ I got a response, that was her Old Windows user account(her Lastname got changed recently)

    Now all I’ve to do is drop her old login(Remove DB mapping as needed) and create new login, fix DB mapping and permissions. Hope this helps…Happy Friday folks 🙂

    Is Microsoft Sql Server Error 15025 Server Principal Already Exists appearing? Would you like to safely and quickly eliminate Microsoft Sql Server which additionally can lead to a blue screen of death?

    When you manually edit your Windows Registry trying to take away the invalid user group or role already exists in the current database keys you’re taking a authentic chance. Unless you’ve got been adequately trained and experienced you’re in danger of disabling your computer system from working at all. You could bring about irreversible injury to your whole operating system. As very little as just 1 misplaced comma can preserve your Pc from even booting every one of the way by!

    Troubleshooting suser_sid Windows XP, Vista, 7, 8 & 10

    Simply because this chance is so higher, we hugely suggest that you make use of a trusted registry cleaner plan like CCleaner (Microsoft Gold Partner Licensed). This system will scan and then fix any Microsoft Sql Server Error 15025 Server Principal Already Exists complications.

    Registry cleaners automate the entire procedure of finding invalid registry entries and missing file references (including the Server error) likewise as any broken hyperlinks inside of your registry.

    Issue with the database principal owns a schema in the database and cannot be dropped

    Backups are made immediately prior to each and every scan providing you with the choice of undoing any changes with just one click. This protects you against doable damaging your pc. Another advantage to these registry cleaners is that repaired registry errors will strengthen the speed and performance of one’s procedure drastically.

    • http://mssqltrek.com/2013/10/18/the-server-principal-already-exists-msg-15025-level-16-state-2-line-1/
    • http://blog.sql-assistance.com/index.php/the-server-principal-domain-loginname
    • http://blogs.msdn.com/b/sqlserverfaq/archive/2010/04/06/unable-to-create-a-login-in-sql-server-2005-and-we-get-the-following-error-the-server-principal-domain-machine-account-already-exists.aspx
    • http://www.handsonsqlserver.com/how-to-resolve-the-the-server-principal-domainloginname-already-exists-error/

    Cautionary Note: Yet again, for those who are not an state-of-the-art consumer it’s very encouraged that you simply refrain from editing your Windows Registry manually. If you make even the smallest error within the Registry Editor it can result in you some serious issues that may even call for a brand new set up of Windows. Not all difficulties attributable to incorrect Registry Editor use are solvable.

    Fixed: sp_change_users_login

    Symptoms of Microsoft Sql Server Error 15025 Server Principal Already Exists
    “Microsoft Sql Server Error 15025 Server Principal Already Exists” appears and crashes the energetic method window.
    Your Personal computer routinely crashes with Microsoft Sql Server Error 15025 Server Principal Already Exists when running the exact same system.
    “Microsoft Sql Server Error 15025 Server Principal Already Exists” is shown.
    Windows operates sluggishly and responds little by little to mouse or keyboard input.
    Your computer periodically “freezes” for the number of seconds in a time.

    Will cause of Microsoft Sql Server Error 15025 Server Principal Already Exists

    Corrupt obtain or incomplete set up of Windows Operating System software program.

    Corruption in Windows registry from a new Windows Operating System-related application adjust (install or uninstall).

    Virus or malware infection which has corrupted Windows method documents or Windows Operating System-related application data files.

    Another method maliciously or mistakenly deleted Windows Operating System-related files.

    Mistakes this sort of as “Microsoft Sql Server Error 15025 Server Principal Already Exists” can be brought about by several different elements, so it really is important that you troubleshoot every of the achievable brings about to forestall it from recurring.

    Simply click the beginning button.
    Variety “command” inside the lookup box… Will not hit ENTER nonetheless!
    Although keeping CTRL-Shift in your keyboard, hit ENTER.
    You’re going to be prompted that has a authorization dialog box.
    Click on Of course.
    A black box will open having a blinking cursor.
    Variety “regedit” and hit ENTER.
    Within the Registry Editor, choose the user group or role already exists in the current database connected key (eg. Windows Operating System) you wish to back again up.
    Within the File menu, choose Export.
    Inside the Preserve In list, pick out the folder in which you wish to save the Windows Operating System backup key.
    Inside the File Title box, sort a reputation for the backup file, these types of as “Windows Operating System Backup”.
    From the Export Vary box, ensure that “Selected branch” is selected.
    Click on Help you save.
    The file is then saved by using a .reg file extension.
    You now use a backup within your suser_sid related registry entry.

    Solution to your problem

    There are actually some manual registry editing measures that can not be talked about in this article due to the high chance involved for your laptop or computer method. If you want to understand more then check out the links below.

    Additional Measures:

    One. Conduct a Thorough Malware Scan

    There’s a probability the Principal Server Sql Server 15025 Error Already Exists Microsoft error is relevant to some variety of walware infection. These infections are malicious and ready to corrupt or damage and possibly even delete your ActiveX Control Error files. Also, it’s attainable that your Microsoft Sql Server Error 15025 Server Principal Already Exists is actually connected to some element of that malicious plan itself.

    2. Clean Disk Cleanup

    The a lot more you employ your computer the extra it accumulates junk files. This comes from surfing, downloading packages, and any sort of usual computer system use. When you don’t clean the junk out occasionally and keep your program clean, it could turn into clogged and respond slowly. That is when you can encounter an Server error because of possible conflicts or from overloading your hard drive.

    Once you clean up these types of files using Disk Cleanup it could not just remedy Microsoft Sql Server Error 15025 Server Principal Already Exists, but could also create a dramatic change in the computer’s efficiency.

    Tip: While ‘Disk Cleanup’ is definitely an excellent built-in tool, it even now will not completely clean up Already Exists discovered on your PC. There are numerous programs like Chrome, Firefox, Microsoft Office and more, that cannot be cleaned with ‘Disk Cleanup’.

    Since the Disk Cleanup on Windows has its shortcomings it is extremely encouraged that you use a specialized sort of challenging drive cleanup and privacy safety application like CCleaner. This system can clean up your full pc. If you run this plan after each day (it could be set up to run instantly) you are able to be assured that your Pc is generally clean, often operating speedy, and always absolutely free of any Server error associated with your temporary files.

    How Disk Cleanup can help

    1. Click your ‘Start’ Button.
    2. Style ‘Command’ into your search box. (no ‘enter’ yet)
    3. When holding down in your ‘CTRL-SHIFT’ important go ahead and hit ‘Enter’.
    4. You will see a ‘permission dialogue’ box.
    5. Click ‘Yes’
    6. You will see a black box open up plus a blinking cursor.
    7. Variety in ‘cleanmgr’. Hit ‘Enter’.
    8. Now Disk Cleanup will start calculating the amount of occupied disk space you will be able to reclaim.
    9. Now a ‘Disk Cleanup dialogue box’ seems. There will be a series of checkboxes for you personally to pick. Generally it will likely be the ‘Temporary Files’ that consider up the vast majority of your disk area.
    10. Verify the boxes that you want cleaned. Click ‘OK’.

    How to repair

    3. System Restore can also be a worthwhile device if you ever get stuck and just desire to get back to a time when your computer system was working ideal. It will work without affecting your pics, paperwork, or other crucial information. You can discover this option with your User interface.

    Already Exists

    Manufacturer

    Device

    Operating System


    Microsoft Sql Server Error 15025 Server Principal Already Exists


    4 out of
    5

    based on
    57 ratings.

     

    Понравилась статья? Поделить с друзьями:
  • Sql ошибка 258
  • Sql ошибка 209
  • Squad ошибка unreal engine 4 crash reporter
  • Sql ошибка 2003
  • Sqlyog ошибка 2058