Ошибка восстановления монопольного доступа sql

  • #1

Здравствуйте! Как восстановить БД SQL server из bak файла? Пишет что не удается восстановить так как БД не в монопольном режиме..

— -Подумал и добавил — —

При восстановлении базы вот такая ошибка:

ЗАГОЛОВОК: Microsoft SQL Server Management Studio
——————————

Ошибка восстановления базы данных «MGMT_DB». (Microsoft.SqlServer.Management.RelationalEngineTa sks)

——————————
ДОПОЛНИТЕЛЬНЫЕ СВЕДЕНИЯ:

System.Data.SqlClient.SqlError: Не удалось получить монопольный доступ, так как база данных используется. (Microsoft.SqlServer.SmoExtended)

Последнее редактирование модератором: 28.02.2019

Не удалось получить монопольный доступ, так как база данных используется

Я
   Надмозг

08.02.18 — 12:57

   SSSSS_AAAAA

1 — 08.02.18 — 13:00

(0) «Я один ее использовал,»

На момент восстановления в базе не должно быть НИКОГО.

   Deon

2 — 08.02.18 — 13:00

(0) Поставь в параметрах «Закрыть существующие соединения»

   Надмозг

3 — 08.02.18 — 13:05

(1) Это очевидно. Я к тому, что я один использовал, и я-то знаю, что я вышел.

(2) ставил, не помогало

  

Надмозг

4 — 08.02.18 — 13:08

Снял в параметрах «создать резервную копию заключительного фрагмента журнала до восстановления», и прокатило.

Странно. А если мне нужна эта копия?

Цитата
Сообщение от qwertehok
Посмотреть сообщение

почему? восстановил из бэкапа и сразу переводишь в online

Ее не нужно переводить в режим онлайн.
База и так восстановится в режиме онлайн.

Цитата
Сообщение от qwertehok
Посмотреть сообщение

USE [master];
DECLARE @KILL VARCHAR(8000) = »;
SELECT @KILL = @KILL + ‘kill ‘ + CONVERT(VARCHAR(5), session_id) + ‘;’
FROM sys.dm_exec_sessions
WHERE database_id  = db_id(‘MyDB’)
EXEC(@KILL);

Вариант так себе. Потому что в процессе убивания одних сессий — могут появиться другие.
Годится только при очень невысокой нагрузке на базу.

И рестриктед юзерс — тоже обычно не прокатывает, потому что … глубоко уважаемые дебилоперы (модератор не разрешает материться) обычно не в состоянии понять концепцию «роли приложения», а уж коннект от ограниченного пользователя и нормальная работа с разрешениями — вообще нечто за гранью фантастики, поэтому 99.99% приложений работают из под сисадмина.

Так что самый рабочий вариант для восстановления — set offline, и восстановление поверх.
Труднее, когда нужно вывести базу на обслуживание, и что-то поделать в ней без пользователей.
И у тебя куча клиентов от приложения, которое вцепляется в коннект (делает реконнект при разрыве соединения) и работающее от сисадмина :-))))
Вот тут кроме как активация logon-триггера, который не дает соединиться ниоткуда, кроме loopback или чего-то в таком духе — вариантов то и нет.

В некоторых случаях требуется перевод БД SQL сервер в монопольный режим доступа (однопользовательский режим базы данных, Single-user Mode) это требуется в случаях выполнения операций, внесения изменений в БД или операций восстановления из резервной копии.  
Так, например, при попытке восстановить рабочую БД, из резервной копии появится сообщение: 
Exclusive access could not be obtained because the database is in use.

Чтобы исправить данное сообщение об ошибке, рекомендуется закрыть все приложения работающие с данной БД, а также вкладки SQL Management Studio, после этого выполнить команду: 

USE [master]
GO
ALTER DATABASE [AdventureWork] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO

где, AdventureWork — это имя базы данных.
Это откатит все текущие транзакции и переведет базу данных в режим работы Single-user Mode. После этого, если 

в этом же окне

запустить операцию восстановления из резервной копии, то ошибка: «Exclusive access…» не повторится.

Для перевода режима работы БД в нормальный многопользовательский режим работы, необходимо выполнить команду:

USE master;
GO
ALTER DATABASE AdventureWorks
SET MULTI_USER;
GO

I want to restore a database from a file (Tasks → Restore → Database; after I select from device and select file) via SQL Server Management Studio.

After that, I get this error:

The operating system returned the error ‘5(Access is denied.)’ while attempting
‘RestoreContainer::ValidateTargetForCreation’ on ‘E:Program FilesMicrosoft SQL
ServerMSSQL10.MSSQLSERVERMSSQLDATAXXXXXX.mdf’.
Msg 3156, Level 16, State 8, Server XXXX, Line 2

How do I fix this problem? Is it a security error?

Uwe Keim's user avatar

Uwe Keim

39.3k56 gold badges174 silver badges291 bronze badges

asked Aug 16, 2010 at 15:03

2xMax's user avatar

1

I recently had this problem. The fix for me was to go to the Files page of the Restore Database dialog and check «Relocate all files to folder».

Restore Database dialog

Uwe Keim's user avatar

Uwe Keim

39.3k56 gold badges174 silver badges291 bronze badges

answered Jun 21, 2013 at 11:13

Jamie Humphries's user avatar

Jamie HumphriesJamie Humphries

3,3382 gold badges18 silver badges21 bronze badges

3

The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.

enter image description here

Greg Bray's user avatar

Greg Bray

14.8k12 gold badges80 silver badges104 bronze badges

answered Aug 16, 2010 at 15:07

SQLMenace's user avatar

SQLMenaceSQLMenace

132k25 gold badges203 silver badges225 bronze badges

2

Well, In my case the solution was quite simple and straight.

I had to change just the value of log On As value.

Steps to Resolve-

  1. Open Sql Server Configuration manager
  2. Right click on SQL Server (MSSQLSERVER)
  3. Go to Properties

enter image description here

  1. change log On As value to LocalSystem

enter image description here

Hoping this will help you too :)

answered Apr 25, 2017 at 15:07

Vikash Pandey's user avatar

Vikash PandeyVikash Pandey

5,4096 gold badges40 silver badges42 bronze badges

1

I just ran into this same problem but had a different fix. Essentially I had both SQL Server and SQL Server Express installed on my computer. This wouldn’t work when I attempted to restore to SQL Express, but worked correctly when I restored it to SQL Server.

answered Mar 16, 2012 at 13:34

Ramone Hamilton's user avatar

1

A good solution that can work is go to files > and check the reallocate all files

Files relocate

DaFois's user avatar

DaFois

2,1878 gold badges26 silver badges43 bronze badges

answered Oct 7, 2019 at 13:37

enter image description hereThe operating system returned the error ‘5(access denied.)’ when restoring database in sql server can be solved by enabling the Relocate all files to folder in the Files options as follows:

answered Apr 5, 2022 at 0:58

P.Githinji's user avatar

P.GithinjiP.Githinji

1,43911 silver badges5 bronze badges

I tried the above scenario and got the same error 5 (access denied). I did a deep dive and found that the file .bak should have access to the SQL service account. If you are not sure, type services.msc in Start -> Run then check for SQL Service logon account.

Then go to the file, right-click and select Security tab in Properties, then edit to add the new user.

Finally then give full permission to it in order to give full access.

Then from SSMS try to restore the backup.

Nathan Tuggy's user avatar

Nathan Tuggy

2,24327 gold badges30 silver badges38 bronze badges

answered Feb 10, 2015 at 0:58

Niroshanth's user avatar

2

I was getting the same error while trying to restore SQL 2008 R2 backup db in SQL 2012 DB. I guess the error is due to insufficient permissions to place .mdf and .ldf files in C drive. I tried one simple thing then I succeeded in restoring it successfully.

Try this:

In the Restore DB wizard windows, go to Files tab, change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will definitely get restores successfully!

Hope this helps you too. Cheers :)

answered Mar 10, 2016 at 8:13

Raja Sekhar's user avatar

There are several causes for this error, I got this error because I checked «Reallocate all files to folder» in the Files tab of Restore Database window but the default path did not exist on my local machine. I had the ldf/mdf files in another folder, once I changed that I was able to restore.

answered Nov 28, 2017 at 0:05

cheriejw's user avatar

cheriejwcheriejw

3643 silver badges13 bronze badges

1

I encountered the same problem, but my setup is a bit different.

  • I run my database in a linux docker container
  • sqlserver management tool in Windows.

What I did was:

sudo docker exec -u root -it sqlserver /bin/bash

This enters the docker container as a root user.

Then:

chmod 777 /path/to/file.bak

777 gives read, write & execute permissions to the file for any group, user

answered Sep 19, 2022 at 16:26

Niels's user avatar

NielsNiels

1961 silver badge11 bronze badges

I found this, and it worked for me:

CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO

answered May 24, 2012 at 22:50

Tom Stickel's user avatar

Tom StickelTom Stickel

19.5k6 gold badges111 silver badges113 bronze badges

2

In my case I had to check the box in Overwrite the existing database (WITH REPLACE) under Options tab on Restore Database page.

The reason I was getting this error: because there was already an MDF file present for the database and it was not getting overwritten.

Hope this will help someone.

answered Jan 27, 2014 at 15:07

Newbee's user avatar

NewbeeNewbee

1,3792 gold badges16 silver badges36 bronze badges

If you’re attaching a database, take a look at the «Databases to attach» grid, and specifically in the Owner column after you’ve specified your .mdf file. Note the account and give Full Permissions to it for both mdf and ldf files.

answered Oct 29, 2014 at 19:53

jgo's user avatar

jgojgo

3722 silver badges12 bronze badges

I had exactly same problem but my fix was different — my company is encrypting all the files on my machines. After decrypting the file MSSQL did not have any issues to accessing and created the DB. Just right click .bak file -> Properties -> Advanced… -> Encrypt contents to secure data.
Decrypting

answered Sep 8, 2017 at 13:50

Radoslaw Jurewicz's user avatar

1

this happened to me earlier today, i was a member of the local server’s admin group and have unimpeded access, or i thought so. I also ticked the «replace» option, even though there is no such DB in the instance.

Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can’t ovewrwrite the existing files. Found out also that the files’ owner is «unknown», i had to change ownership, to the 2 files above so that it is now owned by the local server’s admin group, then renamed it.

Then finally, it worked.

answered Oct 7, 2017 at 6:39

user1465073's user avatar

user1465073user1465073

3158 silver badges22 bronze badges

The account does not have access to the location for backup file.
Take the following steps to access the SQL Server Configuration Manager via Computer Manager easily

  1. Click the Windows key + R to open the Run window.
  2. Type compmgmt.msc in the Open: box.
  3. Click OK.
  4. Expand Services and Applications.
  5. Expand SQL Server Configuration Manager.
  6. Change User Account in Log On As tab .

Now you can Restore Data Base easily

answered Jul 13, 2019 at 19:15

reza.bm's user avatar

reza.bmreza.bm

1711 gold badge3 silver badges8 bronze badges

The fix for me was to go into Options when trying to Restore the database and change the path to the new path.
Here is the screenshot

answered Dec 17, 2019 at 20:37

David A's user avatar

Возможно, вам также будет интересно:

  • Ошибка восстановления диска ключ восстановления на этом диске отсутствует
  • Ошибка восстановления windows файл winload efi
  • Ошибка восстановления itunes 3194 при восстановлении iphone
  • Ошибка восстановление запуска что делать
  • Ошибка воспроизведения ютуб на планшете

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

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