-
#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
1 — 08.02.18 — 13:00
(0) «Я один ее использовал,»
На момент восстановления в базе не должно быть НИКОГО.
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
39.3k56 gold badges174 silver badges291 bronze badges
asked Aug 16, 2010 at 15:03
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».
Uwe Keim
39.3k56 gold badges174 silver badges291 bronze badges
answered Jun 21, 2013 at 11:13
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.
Greg Bray
14.8k12 gold badges80 silver badges104 bronze badges
answered Aug 16, 2010 at 15:07
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-
- Open
Sql Server Configuration manager - Right
click on SQL Server (MSSQLSERVER) - Go to
Properties
- change
log On Asvalue toLocalSystem
Hoping this will help you too 
answered Apr 25, 2017 at 15:07
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
1
A good solution that can work is go to files > and check the reallocate all files
DaFois
2,1878 gold badges26 silver badges43 bronze badges
answered Oct 7, 2019 at 13:37

answered Apr 5, 2022 at 0:58
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
2,24327 gold badges30 silver badges38 bronze badges
answered Feb 10, 2015 at 0:58
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
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
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
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 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
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
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.
answered Sep 8, 2017 at 13:50
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
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
- Click the Windows key + R to open the Run window.
- Type compmgmt.msc in the Open: box.
- Click OK.
- Expand Services and Applications.
- Expand SQL Server Configuration Manager.
- Change User Account in Log On As tab .
Now you can Restore Data Base easily
answered Jul 13, 2019 at 19:15
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







