10.11.13 — 12:48
Подскажите , пожалуйста, создаю базу на новом сервере sql и восстанавливаю в нее данные их архивной копии, сделанной со старого физического сервера sql. Пара баз восстановилась нормально, а остальные стали ругаться таким образом : для восстановления не выбран резервный набор данных. Заранее большое спасибо
1 — 10.11.13 — 12:56
2 — 10.11.13 — 12:58
Читал. На 2008 сервере я указывал при восстановлении файл базы и лога. А в 2012 он не дает, все поля не активны.
3 — 10.11.13 — 12:59
У меня просто копии, модель восстановления на всех базах простая была. А сейчас он требует журнал транзакция, как я понимаю
4 — 10.11.13 — 13:04
(3)
ерунду («требует журнал транзакция») Вы понимаете.
либо не полный список ошибок.
читайте заново
http://msdn.microsoft.com/ru-ru/library/ms186390.aspx
приведите номер ошибки.
5 — 10.11.13 — 13:04
(3) так бэкап полный или инкрементный
6 — 10.11.13 — 13:07
бекап полный
7 — 10.11.13 — 13:11
Номера ошибки нет, просто Выбираю базу данных, пустую, которую создал через 1с , дальше выбираю Задачи — Восстановить — база данных. Открывается окно гдн Источник , выбираю устройство и ище местоположения архива, Назначение — пустая база данных. А вот где Таблица с Восстанавливаемыми резервными наборами данных, которая, как я понимаю, определяет что за архив я буду разворачивать, эта таблица не активна, пустая. А когда все хорошо, она паказывает архив
8 — 10.11.13 — 13:12
9 — 10.11.13 — 13:15
Вначале пишет Чтение заголовка устройств резервного копирования, идет зеленая полоса прогресса, а потом красный крестик Для восстановления не выбран резервный набор данных. Я не понимаю почему ему не нравятся архивы?
10 — 10.11.13 — 13:16
Может установить родной 2008 с которого архивы все делались вместо 2012
11 — 10.11.13 — 13:20
select @@VERSION
что говорит ?
12 — 10.11.13 — 13:23
секундочку
13 — 10.11.13 — 13:23
(9)[Я не понимаю почему ему не нравятся архивы?]
а это к чему ?
14 — 10.11.13 — 13:24
Пишет Microsoft SQL Server 2012 — 11.0.2100.60 (X64)
Feb 10 2012 19:39:15
Copyright (c) Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
15 — 10.11.13 — 13:26
shuhard, раньше получалось же восстановить архив в любую базу, выбирал только расположение самой базы и лога транзакций и все. А сейчас он ничего не дает выбрать, все неактивно Только пишет:
для восстановления не выбран резервный набор данных
16 — 10.11.13 — 13:27
Через запрос пишу
RESTORE DATABASE IP_Bogdanova
FROM DISK = ‘C:IP_Bogdanova.bak’
WITH FILE=1, NORECOVERY;
А он пишет :
Сообщение 3154, уровень 16, состояние 4, строка 1
Резервный набор данных содержит копию базы данных, отличной от существующей базы данных «IP_Bogdanova».
Сообщение 3013, уровень 16, состояние 1, строка 1
RESTORE DATABASE прервано с ошибкой.
17 — 10.11.13 — 13:28
18 — 10.11.13 — 13:29
19 — 10.11.13 — 13:31
не перейти по ссылке (
20 — 10.11.13 — 13:36
(15) напиши ещё сто раз одно и то же
21 — 10.11.13 — 13:38
это мне адресовано?
22 — 10.11.13 — 13:41
короче задница полная, бухи останутся без работы
23 — 10.11.13 — 13:45
24 — 10.11.13 — 14:28
он не дает мне изменить параметры восстановления !
25 — 10.11.13 — 14:38
(0)
9. Если во время выполнения операции восстановления возникает ошибка 3154, перезапишите существующую базу данных используя команду RESTORE DATABASE с опцией WITH REPLACE или выполните восстановление в базу данных с другим именем.
Ошибка 3154 возникает, когда Вы пытаетесь восстановить базу поверх существующей, но существующая база данных была создана оператором CREATE DATABASE с другим набором инструкций, чем при создании базы данных, восстанавливаемой из резервной копии.
26 — 10.11.13 — 14:40
Михаил, скажите пожалуйста, так как можно восстановить в пустую базу данных данные из архива, чтобы сервер не ругался?
27 — 10.11.13 — 14:46
(26)
из (17) узнаёте параметры базы;
создаете с такими же пораметрами новую бд
восстанавливаете.
28 — 10.11.13 — 14:49
Извиняюсь, я уже просто запутался совсем. Уже установил скуль 2008 в котором первоначально все архивы делались. Он теперь пишет ЗАГОЛОВОК: Microsoft SQL Server Management Studio
——————————
При выполнении инструкции или пакета Transact-SQL возникло исключение. (Microsoft.SqlServer.ConnectionInfo)
——————————
ДОПОЛНИТЕЛЬНЫЕ СВЕДЕНИЯ:
RESTORE HEADERONLY прервано с ошибкой. (Microsoft SQL Server, ошибка: 3013)
Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.1600&EvtSrc=MSSQLServer&EvtID=3013&LinkId=20476
——————————
КНОПКИ:
ОК
——————————
29 — 10.11.13 — 14:50
На том скриншоте, который Вы мне прислали надо параметры изменить, куда типа архив будт восстанавливаться, но он мне не дает залесть в параметры требует источник восстановления выбрать, я выбираю, а он пишет
ЗАГОЛОВОК: Microsoft SQL Server Management Studio
——————————
При выполнении инструкции или пакета Transact-SQL возникло исключение. (Microsoft.SqlServer.ConnectionInfo)
——————————
ДОПОЛНИТЕЛЬНЫЕ СВЕДЕНИЯ:
RESTORE HEADERONLY прервано с ошибкой. (Microsoft SQL Server, ошибка: 3013)
Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.1600&EvtSrc=MSSQLServer&EvtID=3013&LinkId=20476
——————————
КНОПКИ:
ОК
——————————
30 — 10.11.13 — 14:55
Кроме архивов SQL неплохо делать стандартную выгрузку из 1С
31 — 10.11.13 — 14:55
баз много, было бы несколько — запросто
32 — 10.11.13 — 14:55
беда совсем
33 — 10.11.13 — 14:56
Никак не зайти в параметры и не выбрать местоположение базы и журнала.
34 — 10.11.13 — 14:59
Ошибка здесь — Выбираю базу данных, пустую, которую создал через 1с — создай просто пустую базу через sql менеджер — в нее востанови базу, а потом укажи путь к ней для сервера 1с
35 — 10.11.13 — 15:00
Забыл сказать, что резервные копии были сжаты средст
вами sql
36 — 10.11.13 — 15:02
маловероятно, что все копии испортились, если их хранили не на флэш.
разверните более ранние архивы.
37 — 10.11.13 — 15:02
Когда создаешь базу через 1с — она уже будет не пустой — в ней будут куча таблиц 1с. если восстанавливать из dt, то да, а если скл — то нужно просто пустая скл-база
38 — 10.11.13 — 15:03
так в пустую и восстанавливаю данные из архива
39 — 10.11.13 — 15:03
скорее всего Вы не тот скл 2008 развернули
скл 2008 и скл 2008 R2 различные версии.
40 — 10.11.13 — 15:05
(38) — пустую базу как создаешь?
41 — 10.11.13 — 15:05
Я всегда это делал, как уже говорил, через меню параметры. Там соответственно проставлял базу и журнал. Сейчас он мне зайти туда не дает пишет Выберите сначала источник восстановления. А выбираю источник пишет ЗАГОЛОВОК: Microsoft SQL Server Management Studio
——————————
При выполнении инструкции или пакета Transact-SQL возникло исключение. (Microsoft.SqlServer.ConnectionInfo)
——————————
ДОПОЛНИТЕЛЬНЫЕ СВЕДЕНИЯ:
RESTORE HEADERONLY прервано с ошибкой. (Microsoft SQL Server, ошибка: 3013)
Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.1600&EvtSrc=MSSQLServer&EvtID=3013&LinkId=20476
——————————
КНОПКИ:
ОК
——————————
42 — 10.11.13 — 15:06
Пустую создаю через значок 1с — создание новой базы
43 — 10.11.13 — 15:06
Вы думаете лучше создавать все только скулем?
44 — 10.11.13 — 15:06
45 — 10.11.13 — 15:06
в свойствах программа пишет просто 2008 без R2
46 — 10.11.13 — 15:07
(43) — конечно
47 — 10.11.13 — 15:07
Михаил, он мне в опции не дает зайти (
48 — 10.11.13 — 15:09
Создал чере скуль — все то же самое
49 — 10.11.13 — 15:10
Михаил, как на Вашем скриншоте, я так всегда и восстанавливал в пустую базу. Но сейчас засада какая-то.
50 — 10.11.13 — 15:12
» А вот где Таблица с Восстанавливаемыми резервными наборами данных, которая, как я понимаю, определяет что за архив я буду разворачивать, эта таблица не активна, пустая.» — значит архивы битые, сразу не все прочитал, там по любому должна быть куча информация от даты создания, названия базы и пр
51 — 10.11.13 — 15:14
Как вы поняли, я не мега спец по СКУЛЮ, читаю Уильяма Станека, но прост осейчас надо все мегасрочно к завтра исправить. А что за таблица я не совсем понимаю?
52 — 10.11.13 — 15:15
Все началось с того, что все работало нормально. Начальник решил вбить в домен этот несчастный сервер. После того, как он его вбил в домен, сервер уже не узнавал сам себя. Ну а разбираться мне крайнему
53 — 10.11.13 — 15:20
Кстати вот эти архивные копии я скопировал на свой внешний жесткий диск, а хранились они на рэйде 10 ssd. Может при копировании на другой тип носителя архивная копия и глючит?
sergey1982
54 — 10.11.13 — 15:20
я уже нифига не понимаю
If you’re doing this with C#, and the physical paths are not the same, you need to use RelocateFiles, as one answer here also mentioned.
For most cases, the below code will work, assuming:
-
You’re just restoring a backup of a database from elsewhere, otherwise meant to be identical. For example, a copy of production to a local Db.
-
You aren’t using an atypical database layout, for example one where the rows files are spread across multiple files on multiple disks.
In addition, the below is only necessary on first restore. Once a single successful restore occurs, the below file mapping will already be setup for you in Sql Server. But, the first time — restoring a bak file to a blank db — you basically have to say, «Yes, use the Db files in their default, local locations, instead of freaking out» and you need to tell it to keep things in the same place by, oddly enough, telling it to relocate them:
var dbDataFile = db.FileGroups[0].Files[0];
restore.RelocateFiles.Add(new RelocateFile(dbDataFile.Name, dbDataFile.FileName));
var dbLogFile = db.LogFiles[0];
restore.RelocateFiles.Add(new RelocateFile(dbLogFile.Name, dbLogFile.FileName));
To better clarify what a typical case would be, and how you’d do the restore, here’s the full code for a typical restore of a .bak file to a local machine:
var smoServer = new Microsoft.SqlServer.Management.Smo.Server(
new Microsoft.SqlServer.Management.Common.ServerConnection(sqlServerInstanceName));
var db = smoServer.Databases[dbName];
if (db == null)
{
db = new Microsoft.SqlServer.Management.Smo.Database(smoServer, dbName);
db.Create();
}
restore.Devices.AddDevice(backupFileName, DeviceType.File);
restore.Database = dbName;
restore.FileNumber = 0;
restore.Action = RestoreActionType.Database;
restore.ReplaceDatabase = true;
var dbDataFile = db.FileGroups[0].Files[0];
restore.RelocateFiles.Add(new RelocateFile(dbDataFile.Name, dbDataFile.FileName));
var dbLogFile = db.LogFiles[0];
restore.RelocateFiles.Add(new RelocateFile(dbLogFile.Name, dbLogFile.FileName));
restore.SqlRestore(smoServer);
db.SetOnline();
smoServer.Refresh();
db.Refresh();
This code will work whether you’ve manually restored this Db before, created one manually with just the name and no data, or done nothing — started with a totally blank machine, with just Sql Server installed and no databases whatsoever.
I am trying to restore a SQL Server backup file for my database, but it is throwing an error as follow:
The backup set holds a backup of a database other than the existing
My database in SQL Server 2008 and the backup file is in 2005.
What can be the problem?
asked Apr 18, 2012 at 7:02
2
I too came across this issue.
Solution :
- Don’t create an empty database and restore the
.bak
file on to it. - Use ‘Restore Database’ option accessible by right clicking the «Databases» branch of the SQL Server Management Studio and provide the database name while
providing the source to restore. - Also change the file names at «Files» if the other database still exists. Otherwise you get «The file ‘…’ cannot be overwritten. It is being used by database ‘yourFirstDb'».
Matthew Lock
13k12 gold badges91 silver badges130 bronze badges
answered Feb 20, 2013 at 11:41
sunil_philipsunil_philip
9,6151 gold badge12 silver badges2 bronze badges
10
Either:
1) Use WITH REPLACE
while using the RESTORE
command (if using the GUI, it is found under Options -> Overwrite the existing database (WITH REPLACE
)).
2) Delete
the older database which is conflicting and restore again using RESTORE
command.
Check the link for more details.
answered Apr 18, 2012 at 7:16
AmarnathAmarnath
8,70610 gold badges54 silver badges80 bronze badges
1
First create a blank database of the same name. Then go for the restore option
Under Options on the left pane don’t forget to select
- Overwrite the existing database
- Preserve the replication settings
That’s it
answered May 15, 2014 at 8:29
HimalayanCoderHimalayanCoder
9,5406 gold badges59 silver badges60 bronze badges
0
I was facing same problem and found the solution by doing this, using SSMS 2014
Just select the Option Overwrite the existing database(WITH REPLACE)
answered Dec 23, 2015 at 10:31
Smit PatelSmit Patel
2,9521 gold badge26 silver badges44 bronze badges
0
This causes always due to version incompatibility.
follow these steps to solve:
Step 1: Create a database with your preferred name. (In our case AdventureWorks)
Step 2: Write click on the database and click on Tasks >> Restore >> Database…
Step 3: On the restore screen go to third selection of Options. Now select the checkbox “Overwrite the existing database (WITH REPLACE)”
Step 4: Click OK. It should successfully restore the database.
Note: When you restore a database WITH REPLACE it will overwrite the old database.
answered Jan 15, 2020 at 13:05
2
USE [master];
GO
CREATE DATABASE db;
GO
CREATE DATABASE db2;
GO
BACKUP DATABASE db TO DISK = 'c:tempdb.bak' WITH INIT, COMPRESSION;
GO
RESTORE DATABASE db2
FROM DISK = 'c:tempdb.bak'
WITH REPLACE,
MOVE 'db' TO 'c:tempdb2.mdf',
MOVE 'db_log' TO 'c:tempdb2.ldf';
answered May 8, 2015 at 14:53
ElsoniElsoni
4614 silver badges2 bronze badges
0
Simple 3 steps:
1- Right click on database → Tasks → restore → Database
2- Check Device
as source and locate .bak (or zipped .bak) file
3- In the left pane click on options
and:
- check Overwrite the existing database.
- uncheck Take tail-log backup before restore
- check Close existing connection to destination database.
Other options are really optional (and important of course)!
answered Oct 11, 2017 at 8:19
Ali SheikhpourAli Sheikhpour
10.2k5 gold badges38 silver badges82 bronze badges
If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:
-- Queries the backup file for the file list in backup set, where Type denotes
-- type of file. Can be L,D,F or S
-- info: https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:TempDB_backup.bak'
GO
You will get results similar to the following:
And then you can use those logical names in the queries:
-- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
RESTORE DATABASE DB
FROM DISK='C:TempDB_backup.bak'
WITH REPLACE,
MOVE 'DB' TO 'E:MSSQLDataDB.mdf', -- "DB" is the mdf logical name from query above
MOVE 'DB_log' TO 'F:MSSQLLogsDB.ldf'; -- "DB_log" is LDF logical name from query above
More info on RESTORE FILELISTONLY
can be found from the SQL Server docs.
answered May 5, 2017 at 7:11
tinonetictinonetic
7,71111 gold badges53 silver badges79 bronze badges
1
Its because the .mdf
and .ldf
Files from the original Db
were locate at maybe c:programFile....
and this info is saved in the Backup!
If you create the same DB on a different SQL Server where the installation is on c:program Files (x86) ....
you can not restore as usually. You need to relocate the path for .mdf
and .ldf
Files.
Therefore:
-
Create a empty DB on the new Server
-
Right click on the empty Db > Tasks > Restore > Database > click Device select your
.bak
Files > Select Db to restore into - click on Files at left side > Select «Relocate all Files to Folder»
- click Options on the left site > click on Overwrite
Done!
Hope it helps!
answered Feb 13, 2015 at 16:17
HELPERHELPER
2513 silver badges2 bronze badges
I had ran into similar problem today. Tried all the above solutions but didn’t worked. So posting my solution here.
Don’t forget to uncheck Tail-long Backup before restore
Hope it help others too!
answered Apr 7, 2015 at 4:15
immayankmodiimmayankmodi
8,1009 gold badges36 silver badges55 bronze badges
0
Also as important is to make sure that, your database name matches the data base name in the backup you are trying to restore. If it does not match, you will get the same error.
answered Oct 23, 2012 at 12:19
1
system.data.sqlclient.sqlerror:The backup set holds a backup of a database other than the existing ‘Dbname’ database
I have came across to find soultion
-
Don’t Create a database with the same name or different database name !Important.
-
right click the database | Tasks > Restore > Database
-
Under «Source for restore» select «From Device»
-
Select .bak file
-
Select the check box for the database in the gridview below
-
To DataBase: «Here You can type New Database Name» (Ex:DemoDB)
-
Don’t select the Existing Database From DropDownlist
-
Now Click on Ok Button ,it will create a new Databse and restore all data from your .bak file .
you can get help from this link even
Hope it will help to sort out your issue…
jpaugh
6,5354 gold badges37 silver badges90 bronze badges
answered Oct 15, 2018 at 7:24
akshay5662akshay5662
2914 silver badges4 bronze badges
1
Before doing anything else, confirm if your backup is Full or Differential. If you’re trying to create a new database out of a differential backup, no matter what you do you will encounter the error.
answered Sep 30, 2014 at 8:07
1
Same issue with me.The solution for me is:
- Right click on the database.
- Select tasks, select restore database.
- Click options on the left hand side.
- Check first option OverWrite the existing database(WITH REPLACE).
- Go to General, select source and destination database.
- Click OK, that’s it
waka
3,3129 gold badges35 silver badges54 bronze badges
answered Sep 26, 2017 at 6:17
I was just trying to solve this issue.
I’d tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the «relocate files» option in the Files property tab.
Hopefully this helps somebody else.
answered Nov 11, 2013 at 15:29
ClintClint
6,1232 gold badges25 silver badges48 bronze badges
Some of you have highly over complicated this. I found this to be extremely simple.
1) Create a database with the same name as your .bak file database name !Important
2) right click the database | Tasks > Restore > Database
3) Under «Source for restore» select «From Device»
4) Select .bak file
5) Select the check box for the database in the gridview below
6) Under «Select a Page» on the right Select «Options»
7) Select the checkbox labeled «Preserve the replication settings(WITH KEEP_REPLICATION)
Now Go back to the General page and click OK to restore the database…That is it.
answered Feb 26, 2014 at 16:27
RolonRolon
411 bronze badge
1
I had to create new db on my local for testing & i had a back up from my prod. I created the db first and tried to run the BAK on top of the new db which produced this error for me. I deleted the db and restored it while sourcing the new db name in the restore screen itself. The db was automatically created on restore.
answered Nov 18, 2013 at 19:27
I got work done through alternate way, using Generate scripts. That did work for me as Backup-Restore didn’t help to resolve the issue due to same error.
answered Dec 1, 2013 at 8:19
Altaf PatelAltaf Patel
1,3511 gold badge17 silver badges28 bronze badges
In the Options, change the «Restore As» file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
answered Oct 13, 2015 at 7:21
You can restore to a new DB, verify the file name syntax, it ll be in the log file, for the new SQL version ll be a «_log» suffix
ad check the overwrite the existing database flag in option tab
Fabio
answered Feb 10, 2015 at 10:54
FabioFabio
113 bronze badges
This helped me to import the back-up file from the system drive
- Create a database with the same name(preferably) as your .bak file database name
- Right click the database > Tasks > Restore > Database
- Under «Source for restore» select «From Device»
- Select the .bak file selecting the path from the system
- Select the check box for the database in the list box below
- Under «Select a Page» on the right Select «Options»
- Select the checkbox labeled «Preserve the replication settings(WITH KEEP_REPLICATION)
- Select the checkbox for Overwrite the existing database(WITH REPLACE)
Now Go back to the General page and click OK to restore the database…
answered Dec 25, 2019 at 14:04
Prajwal BhatPrajwal Bhat
1932 gold badges4 silver badges21 bronze badges
Im sure this problem is related to the files and folders permissions.
answered Nov 18, 2014 at 14:44
PopasPopas
702 silver badges8 bronze badges
I was trying to restore a production database to a staging database on the same server.
The only thing that worked in my case was restore to a new blank database. This worked great, did not try to overwrite production files (which it would if you just restore production backup file to existing staging database). Then delete old database and rename — the files will keep the new temp name but in my case that is fine.
(Or otherwise delete the staging database first and then you can restore to new database with same name as staging database)
answered Apr 22, 2015 at 1:20
mike nelsonmike nelson
20.9k14 gold badges65 silver badges74 bronze badges
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
answered Jul 2, 2019 at 18:36
Ali SadriAli Sadri
1,55014 silver badges15 bronze badges
I had the same issue but on PS. I leave it here in case someone is trying to do the same
Restore-SqlDatabase -ServerInstance "<your instance name>" -Database "<your db name>" -BackupFile "<backup file route>.bak" -ReplaceDatabase
remember to use Set-ExecutionPolicy Unrestricted -Force
and import import-module sqlps
. Don’t forget to set back your Execution Policy back to restricted once you are done.
answered Nov 24, 2021 at 14:49
gui2gui2
518 bronze badges
Usually dealing with .bak files are coming with headaches, a more straight forward way is using sqldump files to transfer databases.
- Generate script of current database you want to move or copy.
- Instead of entire database, select All Tables.
- From the option menu choose save as script, and click on advance button and set the following configs (I am suing MSSQL 2016):
- Now, where you want to import these data, create a new database, switch to this new database (I mean set it as default)
- Finally run the script, all table and data will be imported.
Good Luck.
- List item
answered Jan 19, 2022 at 7:57
Приглашаем разобраться в важных темах – устранения ошибок MS SQL и восстановления базы данных. Получите представление о разных способах устранения проблемы, которые следует использовать при различных обстоятельствах.
Восстановление баз данных
Специалисты пользуются несколькими способами восстановления баз данных (БД). Наиболее простой и удобный – воспользоваться программой (SSMS) SQL Server Management Studio.
Как восстановить
Узнать, где находится SQL Server Management Studio, довольно легко. Microsoft Windows Server 2012 R2 располагается в стандартном перечне программных продуктов. В Microsoft Windows Server 2008 R2 следует зайти в меню Пуск и отыскать Microsoft Windows Server 2012. Там смотреть Microsoft SQL Server Management Studio.
Далее следует ввести тип сервера с именем, а чтобы подтвердить подлинность – информацию, требуемую для прохождения авторизации. Нажать Соединить (Connect).
В левом углу из обозревателя (Object Explorer) раскрыть Базы данных (Server Objects). Из представленного перечня отобрать базу, подлежащую восстановлению либо ту, данные которой будут восстанавливаться. На выбранном файле кликнуть мышкой и в выпавшем перечне выбрать Задачи (Tasks), затем Восстановить (Restore), потом База данных… (Databases …).
Проделанные шаги дадут старт процессу Restore Database, а значит требуемая база данных начнет восстанавливаться. Следует сделать выбор источника для Restore Database.
Чтобы возобновить базу данных, при запуске мастер восстановления сделает попытку автоматом определить очередность файлов резервных копий. В том случае, когда базу данных нужно загружать из определенной папки либо устройства, понадобится:
- Переключить соответствующую кнопку на Устройство (From device).
- Прописать, откуда восстановится БД.
- Выбрать инфобазу, в которую произведется загрузка данных (Destination for restore). Ею может выступать любая БД, которая регистрировалась на SQL Server (в том числе и база, с которой создавалась резервная копия).
В программе реализована возможность указания времени, необходимого для восстановления БД. Для этого необходимо просто кликнуть по кнопке Временная шкала… (Timeline). Если существует скопированный журнал транзакций или checkpoint в нем, то требуемый промежуток времени может быть указан с высокой точностью (вплоть до секунды).
Если требуется провести копирование БД, то во вкладке Файлы (Files) нужно будет прописать путь к файлам выбранной инфобазы.
Настройка дополнительных параметров
Также в программе реализована возможность настройки дополнительных параметров. Выставляя тот или иной флажок, можно регулировать необходимые действия. Следует выбрать соответствующий флажок, чтобы в процессе восстановления БД:
- Которая опубликована не на сервере, где она создавалась, сохранились настройки репликации, поможет отметка «Сохранить параметры репликации). Он важен, если при резервном копировании была реплицирована БД;
- была проведена перезапись файлов БД с именем, которое указывалось в качестве базы назначения – нужно поставить отметку «Перезаписать существующую базу данных»;
- сузить доступность к базе всем, кто не sysadmin, db_owner, dbcreator – нужно поставить флажок «Ограничение доступа к восстановленной базе данных»;
- старту должен предшествовать перевод БД в режим одного пользователя, а по его завершению вернуть в пользование для множества пользователей – поставить отметку «Закрыть существующие соединения»;
- чтобы провести требуемое резервное копирование завершающего фрагмента журнала транзакций, следует поставить отметку «Создание резервной копии заключительного фрагмента журнала перед восстановлением». Если в окошке Временная шкала резервного копирования (Backup Timeline) для временной точки требуется эта резервная копия, то отметка будет поставлена системой, без возможности снятия;
- чтобы после завершения восстановления каждой резервной копии уточнялась необходимость продолжения процесса – следует поставить отметку «Выдавать приглашение перед восстановлением каждой резервной копии» (Prompt before restoring each backup). Достаточно полезен, т.к. после того, как восстановлено определенное количество резервных копий можно остановить дальнейшую цепочку восстановительных процессов.
Настроив все важные параметры следует нажать ОК. Тем самым запустится процесс. Соответствующее уведомление сообщит об его окончании.
Восстановление базы в новое место
Чтобы перенести базу данных MSSQL Server по другому пути каталога либо сделать ее копию, следует знать, как восстановить БД в новую папку. Полезно знать как ее переименовывать. Для этого можно воспользоваться вышеупомянутой программой SSMS и T-SQL.
Подготовка к восстановлению базы данных
Перед стартом процесса восстановления нужно соблюдать ряд требований:
- Когда осуществляется процесс восстановления базы, доступ к ней может быть только у системного администратора. Для остальных пользователей доступ должен быть ограничен.
- Перед восстановлением нужно сделать резервную копию активного журнала транзакций.
- Чтобы восстановить зашифрованную базу необходим доступ к сертификату либо ассиметричному ключу, который применялся в качестве ее шифратора. Не имея доступа к ним, восстановление зашифрованной БД становится невозможным. Потому, такой сертификат следует хранить, пока может понадобиться резервное копирование.
После того, как база данных версии SQL Server 2005 (9.x) либо более поздней, восстановится, произойдет автоматическое обновление, и она станет доступной.
Если присутствуют полнотекстовые индексы
В том случае, когда в БД SQL Server 2005 (9.x) присутствуют полнотекстовые индексы, в момент ее обновления произойдет импорт, сброс либо перестроение. Результат зависит от того, какое значение проставлено в свойствах сервера upgrade_option.
При обновлении такие индексы станут недоступны, если upgrade_option имеет значения:
- 2 в режиме импорта;
- 0 в режиме перестроения.
Продолжительность поцессов импорта и перестроения зависит от того, какой объем занимают данные. Импорт может длиться пару часов, а процесс перестроения – гораздо дольше (может продолжаться в 10 раз дольше).
В том случае, когда выбран процесс Импорт, а доступ к полнотекстовому каталогу отсутствует, то произойдет перестроение одноименных индексов, которые связаны с ним. Для изменения свойств upgrade_option необходимо воспользоваться процедурой sp_fulltext_service.
Соблюдение правил безопасности
Чтобы обезопасить себя, крайне не рекомендуется проводить присоединение либо восстановление БД, которые были получены из ненадежных или вовсе неизвестных источников. Они могут содержать вредоносные коды, способные:
- запускать выполнение инструкций T-SQL, не предусмотренных системой;
- вызывать ошибки в результате изменения схемы либо самой структуры БД
Если БД получена из источников, не внушающих доверия, то перед началом ее использования необходимо:
- протестировать по инструкции DBCC CHECKDB;
- исследовать исходный и иные коды БД, изучить процедуры.
Инструкции RESTORE
На ход реализации этих инструкций влияет факт существования восстанавливаемой базы. Если база:
- присутствует, то разрешения получают пользователи sysadmin, dbcreator, dbo (владелец БД) по умолчанию;
- отсутствует, то пользователям потребуются разрешения CREATE DATABASE.
Разрешения на реализацию таких инструкций выдаются в соответствии с ролями. В соответствии с ними сервер всегда имеет доступ к данным о членстве. Разрешение RESTORE отсутствует у пользователей с ролями db_owner. Причина в том, что членство может быть проверено лишь в тех случаях, когда к базе данных всегда есть доступ и она не повреждена. А это иногда не соблюдается в процессе выполнения инструкций RESTORES.
Пошаговая инструкция восстановления БД в новую папку в SSMS
- Открыть SSMS и произвести подключение к SQL Server Database Engine.
- Щелкнуть мышкой по имени сервера, чтобы развернулось его дерево.
- Кликнуть мышкой на Базы данных, потом – по Восстановить базу данных.
- В разделе Источник выбрать Общие, чтобы определить соответственное расположение и источник копий, подлежащих восстановлению. Пользователю предлагается выбрать нужный вариант (Базы данных либо Устройства). Особенности:
- При выборе Базы данных открывается перечень БД, где можно выбрать нужную. В нем представлены лишь те базы, у которых резервные копии создавались по журналу msdb. Стоит отметить, что для БД на целевом сервере, резервные копии которых поступили с иных серверов, подобный журнал будет отсутствовать. В таких ситуациях следует выбирать вариант Устройство. Это позволит руками прописать файл, а в случае необходимости – обозначить устройство для выполнения восстановления.
- Устройство можно выбрать, воспользовавшись кнопкой обзора (…). В результате появится окошко Выбор устройств резервного копирования. Перейти в окошко Тип носителя резервной копии, в котором из списка выбрать необходимый тип устройства. Если требуется добавить ряд устройств, это можно сделать с помощью кнопки Добавить в окошке Носитель резервной копии. Когда все необходимые устройства добавлены, необходимо вновь перейти на страницу Общие. Для этого следует нажать ОК в списке Носитель резервной копии. Обратившись к списку Источник: Устройство: База данных обозначить название БД, куда будет производиться восстановление. Пользователь может воспользоваться данным списком только при выборе Устройства. Можно выбирать лишь те БД, у которых на отобранном устройстве имеются резервные копии.
- Название новой базы для проведения восстановления автоматом сформируется в поле База данных в разделе Назначение. При желании оно может быть изменено. Для этого желаемое название вводится в окошке База данных.
- Далее перейти к Восстановить до. Пользователь может оставить значение До последней выбранной резервной копии (по умолчанию) либо кликнуть по Временной шкале. При выбре второго варианта всплывет соответствующее окошко Временная шкала …. В нем нужно указывать точное время.
- Необходимые резервные копии для восстановления можно выбрать в соответствующей сетке. В ней отражены все наборы, доступные в выбранном месте. Система сама предложит план восстановления отобранных копий, который будет использован по умолчанию. Он может быть переопределен, если в сетке изменить отобранные элементы.
- Для указания другого места расположения файлов базы, необходимо выбрать страницу Файлы после чего нажать на Переместить все файлы в папку. Следует указать вновь выбранное место расположения папок файлов данных и журнала.
- Если возникла необходимость – провести настройку параметров, как было рассказано выше.
Чтобы начать процесс, в котором будет восстанавливаться БД в новую папку с возможностью переименовывать ее, можно воспользоваться инструкциями Transact-SQL.
Как просмотреть отчет
Стандартный отчет «События резервного копирования и восстановления» позволяет получить сведения о том, когда проводилось:
- Резервное копирование определенной БД;
- операции восстановления базы MS SQL из них.
Данный отчет включает данные, касающиеся создания резервных копий:
- время, затраченное на это в среднем (Average Time Taken For Backup Operations);
- операции, которые прошли успешно (Successful Backup Operations);
- ошибки, которые были допущены (Backup Operation Errors);
- удачно прошедших восстановлений баз (Successful Restore Operations).
Чтобы он начал формироваться, следует в Обозревателе объектов выбрать нужную БД и щелкнуть по ней мышкой. Выбрать в меню Отчеты, а затем – Стандартный отчет. После этого кликнуть на События резервного копирования и восстановления.
Чтобы просмотреть информацию из сформированного отчета следует выбрать нужную группировку и раскрыть данные по ней.
Для восстановления поврежденной БД можно воспользоваться еще одним инструментом.
Как исправить ошибки в MS SQL с помощью Recovery Toolbox for SQL Server
Для восстановления поврежденной базы данных можно обратиться к помощи Recovery Toolbox for SQL Server. Для исправления ошибки (Error), следует воспользоваться пошаговой инструкцией восстановления данных из файла *.mdf, который был поврежден. Для этого необходимо:
- Скачать Recovery Toolbox for SQL Server.
- Установить программу следуя инструкциям и запустить ее.
- Из списка файлов выбрать файл *.mdf, который был поврежден.
- Осуществить предварительный просмотр тех данных, которые в процессе выполнения программы могут быть подвергнуты извлечению из базы MS SQL сервер, которая подверглась повреждению.
- Выбрать наиболее приемлемый способ, которым будут экспортироваться данные:
- сохранением на диск в качестве SQL-скрипта;
- выполнением SQL-скрипта в самой БД.
- Произвести выборку информации, требующей восстановления и сохранения.
- Начать восстановление нажатием Start recovery.
Данная программа создавалась, чтобы облегчить процесс восстановления поврежденных БД. Специально разработанная, оптимизированная для восстановления SQL Server, утилита поможет устранить ошибки и внести правки в разные типы повреждений *.mdf файлов и базы данных MS SQL Server.
Как становится понятно, для исправления ошибок и восстановления БД необходимо уметь пользоваться различными инструментами. Читайте, изучайте материалы по данной теме. Если возникнут вопросы – обязательно задавайте.
Также приглашаем на специальный курс по MS SQL в Otus.
Perform the following commands in SQL Server Management Studio (SSMS) on the SQL Server instance you are trying to restore the database to.
Verify BAK File
RESTORE VERIFYONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
The backup set on file 1 is valid.
Possible Errors
If the check terminates abnormally then the cause could be because one of these checks have failed:
Checks performed by RESTORE VERIFYONLY include:
- That the backup set is complete and all volumes are readable.
- Some header fields of database pages, such as the page ID (as if it were about to write the data).
- Checksum (if present on the media).
- Checking for sufficient space on destination devices.
Reference: RESTORE Statements — VERIFYONLY (Transact-SQL) (Microsoft | SQL Docs)
Check the BAK Fileheader
RESTORE HEADERONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
BackupName BackupDescription BackupType ExpirationDate Compressed Position DeviceType UserName ServerName DatabaseName DatabaseVersion DatabaseCreationDate BackupSize FirstLSN LastLSN CheckpointLSN DatabaseBackupLSN BackupStartDate BackupFinishDate ........ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ........ NULL NULL 1 NULL 0 1 2 NT SERVICESQLSERVERAGENT NOTHING StackExchange 782 2019-07-24 09:17:00.000 1688399872 568000013810400037 568000013813600001 568000013810400037 568000013524000037 2020-01-15 19:25:27.000 2020-01-15 19:25:29.000 ........
Check the Contents of the BAK File
RESTORE FILELISTONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
LogicalName PhysicalName Type FileGroupName Size MaxSize FileId CreateLSN DropLSN UniqueId ReadOnlyLSN ReadWriteLSN BackupSizeInBytes SourceBlockSize FileGroupId LogGroupGUID DifferentialBaseLSN DifferentialBaseGUID IsReadOnly IsPresent TDEThumbprint ------------------------ ---------------------------------------------- ---- ---------------- ------------ --------------- ------- ------------------- -------- ------------------------------------ ------------------- ------------------ ------------------ --------------- ----------- ------------- -------------------- ------------------------------------ ---------- --------- -------------- StackExchange C:SQLSQL_DATAStackExchange.mdf D PRIMARY 2623537152 35184372080640 1 0 0 725120E9-8DF3-4E09-9A89-94433A6EB49B 0 0 1687224320 4096 1 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 0 1 NULL StackExchange_DefRO C:SQLSQL_DATAStackExchangeRO.ndf D DEFAULTRO 5242880 35184372080640 3 89000000045300001 0 05C6BA44-123A-4749-8FB5-A0A16EF49A51 102000000014600005 90000000013100004 131072 4096 2 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 1 1 NULL StackExchange_PUBL_SNAP C:SQLSQL_DATAStackExchange_PUBL_SNAP.ndf D PUBL_SNAP_DBASE 5242880 35184372080640 4 286000001633700001 0 DCA761C4-6260-4BE3-8280-64099C98911D 0 0 131072 4096 3 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 0 1 NULL StackExchange_log C:SQLSQL_LOGSStackExchange_log.ldf L NULL 21798322176 2199023255552 2 0 0 364124B1-081E-45C5-971C-2CD1CBBF13EC 0 0 0 4096 0 NULL 0 00000000-0000-0000-0000-000000000000 0 1 NULL
If the Steps Fail
If any of the above steps fail, then you will have to determine what the issue is. The RESTORE ...
command should provide enough information to assist you in finding the root cause.
Example Solutions
If the backup file is corrupt, then you will have to find a backup file that works.
If the disk is full, then you will have to add additional space.
If all else fails, then you might have to open a case with Microsoft Support.
Best Practice
(emphasis mine)
Test your backups!
You do not have a restore strategy until you have tested your backups. It is very important to thoroughly test your backup strategy for each of your databases by restoring a copy of the database onto a test system. You must test restoring every type of backup that you intend to use. It is also recommended that once you restore the backup, you perform database consistency checks via DBCC CHECKDB of the database to validate the backup media was not damaged.
Reference: Back Up and Restore of SQL Server Databases (Microsoft | SQL Docs)
Summary:
This blog will describe solutions to fix the ‘SQL database restore failed, database in use’ error. These solutions include disconnecting active connections (users and processes) to the database and by using Stellar Toolkit for MS SQL software to recover SQL database (db) from corrupt db or backup (.bak) file. The solutions apply to MS SQL Server 2019, 2017, 2016, 2014 and lower versions.
Contents
- Reasons behind ‘SQL Database Restore Failed, Database in Use’ Error
- Before We Begin
- How to Fix ‘can’t restore SQL database because it is in use’ Problem?
- What if the problem still persists?
- Conclusion
When trying to restore SQL Server database from backup, it is common to receive an error message that reads as follows:
Restored failed for Server ‘xxx’ (Microsoft.SqlServer.SmoExtended)
Additional Information: System.Data.SqlClient.SqlError: Exclusive access could not be obtained because the database is in use.
Reasons behind ‘SQL Database Restore Failed, Database in Use’ Error
Below are some reasons that could interfere with the restore process and throw the ‘restore of database failed because the database is in use’ error:
- You are connected to the database you are trying to restore.
- While using SQL Server Management Studio (SSMS) to do a database restore, you have more than one window open in it.
- Other users are connected to the master db.
Now, we will discuss solutions to fix the error.
Tip: SQL Server database can be restored from the backup (.bak) file. But, the database restore operation may fail if the .bak file is corrupt. Use Stellar Toolkit for MS SQL software that comes with an efficient SQL backup extractor tool designed to help database administrators recover SQL database from corrupted backup (.BAK) file. The software supports SQL Server 2019, 2017, 2016, 2014, 2012, & older versions.
Before We Begin
Before proceeding with resolving the error – exclusive access could not be obtained because the database is in use, make sure to meet the following prerequisites:
- SQL Server, of any version, must be installed on your system.
- You will need SQL Server Management Studio (SSMS) installed on your computer.
How to Fix ‘can’t restore SQL database because it is in use’ Problem?
When attempting to restore SQL Server db, make sure there are no active connections. If someone is using the database, the restore operation will fail. To resolve the issue, you will need to disconnect the active users. You can do so, by following any of these methods:
NOTE: Before disconnecting the users, use SQL stored procedure ‘sp_who’ to check all users currently using the db. If you find users performing some important tasks, notify those users before disconnecting them. For detailed information on sp_who, refer to this link. If you don’t want to notify users, skip to method 2.
Method 1 – Close the existing connections to the database
To close existing connections to SQL db, follow these steps:
Step 1: Open SSMS and connect to the db.
Step 2: After connecting to the database, Object Explorer panel will appear on the left side of the SSMS window.
Step 3: In Object Explorer panel, right-click Databases, and then select Restore Database.
Step 4: In Restore Database dialog box, do the following:
- Select one of the databases to restore.
- In the left panel, click Options.
Step 5: In Options page, check the checkbox labeled, ‘close existing connections to destination database’.
Once the SQL Server connections are closed, proceed with the restore operation.
Method 2 –Change from multiple-user mode to single-user mode
Changing the multiple-user mode by default to single user mode will disconnect all the connected users. This option can be used, if you want to disconnect all the users without notifying them.
To force users to go offline (i.e. disconnect) from SQL Server, set the db from multiple-user mode to single-user mode by following these steps:
Step 1: Open SSMS, connect to the database.
Step 2: In Object Explorer window, select New Query. Copy and paste the below T-SQL code snippet into the query window, and then click Execute:
USE master; GO ALTER DATABASE AdventureWorks2012 SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO
Executing the above code will change the database to single-user mode.
Method 3 – Restart the SQL Server Service
You can also disconnect the users by restarting the SQL service. You can restart the service by using SQL Server Configuration Manager, SSMS, services console, or the command line.
NOTE: Use this method as a last resort. That’s because, you may only need to restore a single db, but restarting the server will kill connections to all databases.
Steps to restart the service from SQL Server Configuration Manager are as follows:
Step 1: Browse SQL Server Configuration Manager using any of the following path:
SQL Server 2019 C:WindowsSysWOW64SQLServerManager15.msc
SQL Server 2017 C:WindowsSysWOW64SQLServerManager14.msc
SQL Server 2016 C:WindowsSysWOW64SQLServerManager13.msc
SQL Server 2014 C:WindowsSysWOW64SQLServerManager12.msc
SQL Server 2012 C:WindowsSysWOW64SQLServerManager11.msc
Step 2: In the left pane of SQL Server Configuration Manager window, click SQL Server Services. And in the right pane, right-click SQL Server service, and Stop and Start it.
Step 3: Click OK to exit the SQL Server Configuration Manager.
What if the problem still persists?
If the issue still persists, likely there is a problem with your database or the backup file, used for restoring the database, is corrupt. In that case, use Stellar Toolkit for MS SQL. The software can recover db from a corrupt SQL Server. It can also extract a database – from corrupt backup (.bak) files – that need to be restored.
Stellar Toolkit for MS SQL software can also help you reset lost or forgotten SQL Server Administrator and user passwords. You can read the software review done by MVP from here.
To restore database from corrupt SQL Server backup (.bak) file by using the software, follow these steps:
Step 1: Download, install and launch Stellar Toolkit for MS SQL software.
Step 2: In software’s user interface, select Extract from MS SQL Backup.
Step 3: In Stellar Backup Extractor for MS SQL window, click Select File to choose the .bak file.
NOTE: Choose ‘Search in Folder’ option, if you do not know the file location.
Step 4: After selecting the .bak file, click Scan.
Step 5: The BackupSet window appears with details of all the backups.
Step 6: Choose the .bak file you want to recover from the Backup Type list, and then click Next to proceed with the scanning process.
Step 7: Once scanning is complete, a dialog box appears displaying the number of total records available in the backup file.
Step 8: The software shows a preview of the database records.
Step 9: To save the recovered .bak file, click Save on File menu.
Step 10: In the window that pops-up, choose MSSQL under Save As, and then click Browse to select the location to save the recovered file. Click OK.
Step 11: Choose New Database or Live Database under Saving Options. Next, specify details required in Connect to Server section, and then click Connect.
Step 12: Click OK when the ‘Recovery process successfully completed’ message appears.
The recovered file will get saved in the selected location.
You can watch the complete video from here:
Conclusion
This blog explained how to fix the SQL database restore failed, database in use problem. You can disconnect active users by closing the existing connections or by changing from multiple-user mode to single-user mode. Or, disconnect all the users by restarting the SQL Server service. But, if you still have issues restoring the db, Stellar SQL Database Toolkit can come in handy. It helps resolving the issue by repairing the corrupt SQL db or by recovering the SQL Server backup file.
About The Author
Priyanka Chauhan
Priyanka is a technology expert working for key technology domains that revolve around Data Recovery and related software’s. She got expertise on related subjects like SQL Database, Access Database, QuickBooks, and Microsoft Excel. Loves to write on different technology and data recovery subjects on regular basis. Technology freak who always found exploring neo-tech subjects, when not writing, research is something that keeps her going in life.
SQL Server 2012 Troubleshooting: Restore of database failed
Table of Contents
- Problem
- Solution
- References
Problem
From within SQL Server Management Studio (SSMS), you attempt to restore a SharePoint Server 2013 database, but then experience this error message:
TITLE: Microsoft SQL Server Management Studio ------------------------------ Restore of database 'YOURDATABASE' failed. (Microsoft.SqlServer.Management.RelationalEngineTasks) ------------------------------ ADDITIONAL INFORMATION: System.Data.SqlClient.SqlError: The operating system returned the error '32(The process cannot access the file because it is being used by another process.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'D:Program FilesMicrosoft SQL ServerMSSQL11.CSSPMSSQLDATAYOURDATABASE.mdf'. (Microsoft.SqlServer.SmoExtended) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer= 11.0.5058.0+((SQL11_PCU_Main).140514-1820+)&LinkId=20476
The solution is simple and involves the databases files Relocate all files to folder parameter.
Solution
- In SSMS, launch the Restore Database dialog,
- Select Files, and then enable Relocate all files to folder.
- Click OK.
References
- Restore a Database Backup (SQL Server Management Studio)
Одинесю
26.05.15 — 13:14
Модель восстановления — Полная. Имеется Полная резервная копия базы. При попытке восстановления выпадает ошибка System.Data.SqlClient.SqlError: Инструкцию BACKUP LOG невозможно выполнить, так как не существует резервной копии текущей базы данных. (Microsoft.SqlServer.SmoExtended)
Подскажите, что может быть?
PS Восстанавливаю через Management Studio.
fisher
1 — 26.05.15 — 13:17
Первый раз восстанавливаешь? Тогда что-то не так сделал.
Heckfy
2 — 26.05.15 — 13:17
Телепатирую: у вас файл не фулл бекапа, а дифф.
Jaap Vduul
3 — 26.05.15 — 13:27
Наверное, включена опция «Take tail-log backup before restore»
Одинесю
4 — 26.05.15 — 13:34
(3) При создании резервной копии?
Одинесю
5 — 26.05.15 — 13:34
(2) Фулл
Alexey_Morov
6 — 26.05.15 — 13:35
(3)
Провёл восстановление своей базы при указанных параметрах (полная модель восстановления). Всё отлично и на MS SQL 2005, 2008, 2012.
Может быть проблема в том, что восстанавливается бэкап от старшей версии MS SQL на младшей (т.е. бэкап, сделанный в 2012 на, допустим, 2005ом)?
Одинесю
7 — 26.05.15 — 13:35
(1) У себя на копии делал раньше — все нормально восстанавливалось.
Одинесю
8 — 26.05.15 — 13:36
(6) Наоборот на 14 восстанавливаю копию, созданную на 2008, но я так делал уже.
Alexey_Morov
9 — 26.05.15 — 13:39
(1)
Непонятно причём тут BACKUP LOG, если делается наоборот восстановление?
leonidkorolev
10 — 26.05.15 — 13:39
скрипт сюда выложи
Jaap Vduul
11 — 26.05.15 — 13:39
(4) При восстановлении естественно.
Jaap Vduul
12 — 26.05.15 — 13:39
(9) см. (3)
Heckfy
13 — 26.05.15 — 13:40
(5) А я говорю Дифф.
Alexey_Morov
14 — 26.05.15 — 13:42
(13)
Не, при диффе должна быть другая ошибка.
(12) Выложи, пожалуйста, скриншоты.
Jaap Vduul
15 — 26.05.15 — 13:42
Одинесю
16 — 26.05.15 — 13:46
(14) Скриншот чего, я через Мэнэджмент Студио загружаю, вот полное описание ошибки, сейчас покажу окно настройки копирования
===================================
Ошибка восстановления базы данных «Aksol_UPP». (Microsoft.SqlServer.Management.RelationalEngineTasks)
——————————
Расположение программы:
в Microsoft.SqlServer.Management.RelationalEngineTasks.RestoreDatabaseTaskFormComponent.PerformTask(ITaskExecutionContext context)
в Microsoft.SqlServer.Management.RelationalEngineTasks.RestoreDatabaseTaskFormComponent.Perform(ITaskExecutionContext context)
в Microsoft.SqlServer.Management.TaskForms.TaskExecutionManager.ExecuteTaskSequence(ISfcScriptCollector collector)
===================================
System.Data.SqlClient.SqlError: Инструкцию BACKUP LOG невозможно выполнить, так как не существует резервной копии текущей базы данных. (Microsoft.SqlServer.SmoExtended)
——————————
Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=12.0.2000.8+((SQL14_RTM).140220-1752)&LinkId=20476
——————————
Расположение программы:
в Microsoft.SqlServer.Management.Smo.RestorePlan.Execute()
в Microsoft.SqlServer.Management.RelationalEngineTasks.RestoreDatabaseTaskFormComponent.PerformTask(ITaskExecutionContext context)
Jaap Vduul
17 — 26.05.15 — 13:48
(16) см. (15)
Одинесю
18 — 26.05.15 — 13:50
Одинесю
19 — 26.05.15 — 13:50
(17) Сейчас
Одинесю
20 — 26.05.15 — 13:53
Alexey_Morov
21 — 26.05.15 — 13:53
(20) Вот. Наверняка эта ошибка из-за двух галок «Создать резервную копию…»).
Alexey_Morov
22 — 26.05.15 — 13:54
Надо срочно отключить эти галки, так как они мешают при проведении восстановления полного бэкапа.
Одинесю
23 — 26.05.15 — 13:56
(22) Я пробовал…
Одинесю
24 — 26.05.15 — 13:58
(22) Вроде пошло, сделал кроме отключения галок еще и NORECOVERY, вышла уже другая ошибка, что база отличается. Спасибо, буду дальше пробовать.
Jaap Vduul
25 — 26.05.15 — 14:00
(24) Включи «Перезаписать существующую…»
Господин ПЖ
26 — 26.05.15 — 14:00
>вышла уже другая ошибка, что база отличается
у новой базы id другой поставь галку replace
Alexey_Morov
27 — 26.05.15 — 14:03
(26)
Согласен. Должно помочь.
Одинесю
28 — 26.05.15 — 14:12
(26) (27) Спасибо!
Одинесю
29 — 26.05.15 — 14:13
(25) Спасибо!
- Remove From My Forums
-
Question
-
Hi ,
I tried to restore database in sql server 2012 in windows 8. but getting this error , there are several files which already worked before in restoration now not working :
TITLE: Microsoft SQL Server Management Studio
——————————Restore of database ‘classifiedspak’ failed. (Microsoft.SqlServer.Management.RelationalEngineTasks)
——————————
ADDITIONAL INFORMATION:System.Data.SqlClient.SqlError: BACKUP LOG cannot be performed because there is no current database backup. (Microsoft.SqlServer.SmoExtended)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.2100.60+((SQL11_RTM).120210-1846+)&LinkId=20476
——————————
BUTTONS:OK
——————————
Thank You , Shan Ali Khan
Answers
-
You are getting this error because the database you are trying to restore to is not the same from which the backups were taken. The backups were taken from different database and you are trying to restore to a different database.
You have 2 options here.
- Use WITH REPLACE while using the RESTORE command. This will overwrite the existing database and restore the database state represented by the backup files.
- Delete the database to which you are trying to restore to and restore again using RESTORE command. This will create a new database with the state represented by the backup files.
Please note that in both these options you will lose the existing data of the database you are trying to restore to.
Refer to
http://blog.sqlauthority.com/2007/09/27/sql-server-fix-error-3154-the-backup-set-holds-a-backup-of-a-database-other-than-the-existing-database/ for more details about the error you are facing.Refer to http://msdn.microsoft.com/en-us/library/ms186858.aspx for more details about the WITH REPLACE option.
If this does not help, can you please share more details about your scenario. Like Which database was backed up? Where are those files? Which database are you trying to restore to?
Vatsalya — MSFT The views and opinions expressed herein are those of the author and do not necessarily reflect the views of Microsoft.
- Edited by
Saturday, November 10, 2012 4:15 PM
Added reference link. - Marked as answer by
Shan Khan
Monday, November 12, 2012 7:38 AM
- Remove From My Forums
-
Question
-
Hi ,
I tried to restore database in sql server 2012 in windows 8. but getting this error , there are several files which already worked before in restoration now not working :
TITLE: Microsoft SQL Server Management Studio
——————————Restore of database ‘classifiedspak’ failed. (Microsoft.SqlServer.Management.RelationalEngineTasks)
——————————
ADDITIONAL INFORMATION:System.Data.SqlClient.SqlError: BACKUP LOG cannot be performed because there is no current database backup. (Microsoft.SqlServer.SmoExtended)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.2100.60+((SQL11_RTM).120210-1846+)&LinkId=20476
——————————
BUTTONS:OK
——————————
Thank You , Shan Ali Khan
Answers
-
You are getting this error because the database you are trying to restore to is not the same from which the backups were taken. The backups were taken from different database and you are trying to restore to a different database.
You have 2 options here.
- Use WITH REPLACE while using the RESTORE command. This will overwrite the existing database and restore the database state represented by the backup files.
- Delete the database to which you are trying to restore to and restore again using RESTORE command. This will create a new database with the state represented by the backup files.
Please note that in both these options you will lose the existing data of the database you are trying to restore to.
Refer to
http://blog.sqlauthority.com/2007/09/27/sql-server-fix-error-3154-the-backup-set-holds-a-backup-of-a-database-other-than-the-existing-database/ for more details about the error you are facing.Refer to http://msdn.microsoft.com/en-us/library/ms186858.aspx for more details about the WITH REPLACE option.
If this does not help, can you please share more details about your scenario. Like Which database was backed up? Where are those files? Which database are you trying to restore to?
Vatsalya — MSFT The views and opinions expressed herein are those of the author and do not necessarily reflect the views of Microsoft.
- Edited by
Saturday, November 10, 2012 4:15 PM
Added reference link. - Marked as answer by
Shan Khan
Monday, November 12, 2012 7:38 AM
SQL Server 2014 Developer SQL Server 2014 Enterprise SQL Server 2014 Enterprise Core SQL Server 2014 Standard Еще…Меньше
Проблемы
Предположим, что вы создали базу данных клонов с включенным хранилищем запросов в экземпляре SQL Server 2014. При восстановлении базы данных копии в другом экземпляре SQL Server происходит сбой восстановления, и появляется следующее сообщение об ошибке:
Восстановление database_name базы данных завершилось сбоем. (Microsoft. SqlServer. Management. RelationalEngineTasks) System. Data. SqlClient. SqlError: восстановление базы данных аварийно завершается. (Microsoft.SqlServer.SmoExtended)
Кроме того, системное утверждение заносится в журнал ошибок SQL Server.
Решение
Эта проблема устранена в следующем накопительном обновлении SQL Server:
Накопительное обновление 3 для SQL Server 2014 с пакетом обновления 2
Все новые накопительные обновления для SQL Server содержат все исправления и все исправления для системы безопасности, которые были включены в предыдущий накопительный пакет обновления. Ознакомьтесь с самыми последними накопительными обновлениями для SQL Server.
Последнее накопительное обновление для SQL Server 2014
Статус
Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».
Ссылки
Ознакомьтесь с терминологией , которую корпорация Майкрософт использует для описания обновлений программного обеспечения.
Нужна дополнительная помощь?
Perform the following commands in SQL Server Management Studio (SSMS) on the SQL Server instance you are trying to restore the database to.
Verify BAK File
RESTORE VERIFYONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
The backup set on file 1 is valid.
Possible Errors
If the check terminates abnormally then the cause could be because one of these checks have failed:
Checks performed by RESTORE VERIFYONLY include:
- That the backup set is complete and all volumes are readable.
- Some header fields of database pages, such as the page ID (as if it were about to write the data).
- Checksum (if present on the media).
- Checking for sufficient space on destination devices.
Reference: RESTORE Statements — VERIFYONLY (Transact-SQL) (Microsoft | SQL Docs)
Check the BAK Fileheader
RESTORE HEADERONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
BackupName BackupDescription BackupType ExpirationDate Compressed Position DeviceType UserName ServerName DatabaseName DatabaseVersion DatabaseCreationDate BackupSize FirstLSN LastLSN CheckpointLSN DatabaseBackupLSN BackupStartDate BackupFinishDate ........ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ........ NULL NULL 1 NULL 0 1 2 NT SERVICESQLSERVERAGENT NOTHING StackExchange 782 2019-07-24 09:17:00.000 1688399872 568000013810400037 568000013813600001 568000013810400037 568000013524000037 2020-01-15 19:25:27.000 2020-01-15 19:25:29.000 ........
Check the Contents of the BAK File
RESTORE FILELISTONLY FROM DISK = 'T:DIRECTORYDATAWAREHOUSE_FULL_20200115_190000.bak'
This should provide you with a result set that looks like this:
LogicalName PhysicalName Type FileGroupName Size MaxSize FileId CreateLSN DropLSN UniqueId ReadOnlyLSN ReadWriteLSN BackupSizeInBytes SourceBlockSize FileGroupId LogGroupGUID DifferentialBaseLSN DifferentialBaseGUID IsReadOnly IsPresent TDEThumbprint ------------------------ ---------------------------------------------- ---- ---------------- ------------ --------------- ------- ------------------- -------- ------------------------------------ ------------------- ------------------ ------------------ --------------- ----------- ------------- -------------------- ------------------------------------ ---------- --------- -------------- StackExchange C:SQLSQL_DATAStackExchange.mdf D PRIMARY 2623537152 35184372080640 1 0 0 725120E9-8DF3-4E09-9A89-94433A6EB49B 0 0 1687224320 4096 1 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 0 1 NULL StackExchange_DefRO C:SQLSQL_DATAStackExchangeRO.ndf D DEFAULTRO 5242880 35184372080640 3 89000000045300001 0 05C6BA44-123A-4749-8FB5-A0A16EF49A51 102000000014600005 90000000013100004 131072 4096 2 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 1 1 NULL StackExchange_PUBL_SNAP C:SQLSQL_DATAStackExchange_PUBL_SNAP.ndf D PUBL_SNAP_DBASE 5242880 35184372080640 4 286000001633700001 0 DCA761C4-6260-4BE3-8280-64099C98911D 0 0 131072 4096 3 NULL 568000013524000037 707694EC-A36C-444A-8879-C807B2137455 0 1 NULL StackExchange_log C:SQLSQL_LOGSStackExchange_log.ldf L NULL 21798322176 2199023255552 2 0 0 364124B1-081E-45C5-971C-2CD1CBBF13EC 0 0 0 4096 0 NULL 0 00000000-0000-0000-0000-000000000000 0 1 NULL
If the Steps Fail
If any of the above steps fail, then you will have to determine what the issue is. The RESTORE ...
command should provide enough information to assist you in finding the root cause.
Example Solutions
If the backup file is corrupt, then you will have to find a backup file that works.
If the disk is full, then you will have to add additional space.
If all else fails, then you might have to open a case with Microsoft Support.
Best Practice
(emphasis mine)
Test your backups!
You do not have a restore strategy until you have tested your backups. It is very important to thoroughly test your backup strategy for each of your databases by restoring a copy of the database onto a test system. You must test restoring every type of backup that you intend to use. It is also recommended that once you restore the backup, you perform database consistency checks via DBCC CHECKDB of the database to validate the backup media was not damaged.
Reference: Back Up and Restore of SQL Server Databases (Microsoft | SQL Docs)
- Remove From My Forums
-
Question
-
i have .bak file downloaded from internet , and i also have istalled sql server 2012.
my problem that i can not restore this .bak file and get this error massage :
TITLE: Microsoft SQL Server Management Studio
——————————
Restore of database ‘SRO_VT_SHARD’ failed. (Microsoft.SqlServer.Management.RelationalEngineTasks)
——————————
ADDITIONAL INFORMATION:
System.Data.SqlClient.SqlError: The operating system returned the error ‘5(Access is denied.)’ while attempting ‘RestoreContainer::ValidateTargetForCreation’ on ‘C:Program FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATASRO_VT_SHARD.mdf’. (Microsoft.SqlServer.SmoExtended)For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.2100.60+((SQL11_RTM).120210-1846+)&LinkId=20476
— .bak file version = 661 10 50 1600 = sql server 2008R
— my sql version = Microsoft SQL Server 2012 — 11.0.2100.60 (Intel X86)
any help please
Answers
-
Hello Alaa — The message «System.Data.SqlClient.SqlError: The operating system returned the error
‘5(Access is denied.)’», itself indicating permission issues while restoring on the path «C:Program
FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATA»Few Possible Solutions:
- Change your SQL Server service account to an identity that has permissions. For testing purpose you can use «Local System», restart the service and perform the restoration again. It should succeed.
- OR You can create a folder on root of C or D drive & give full control to everyone and then try restoration again by changing the path of restoration file to these drives/ folders by using WITH MOVE option or by using GUI
- OR You can talk to your server support team and ask them to give full control/ permission to SQL Server service account on the folder «C:Program
FilesMicrosoft SQL ServerMSSQL10_50.MSSQLSERVERMSSQLDATA» and then try your restore action again
Hope this helps !
Good Luck!
Please Mark This As Answer if it solved your issue.
Please Vote This As Helpful if it helps to solve your issue- Marked as answer by
Thursday, August 6, 2015 9:57 AM
Restoration of a database from a backup file sometimes can be very tricky. Especially when you don’t know on what server (what environment or what SQL Server version) it was taken. Sometimes you, as a DBA, are just asked to restore database from a given backup on the pointed server. You have got a backup file, you do everything as always but for some reason, the restore operation fails.
Restore of database failed
In this blog post, I describe what is the reason behind the below error.
Priyanka Chauhan
Priyanka is a technology expert working for key technology domains that revolve around Data Recovery and related software’s. She got expertise on related subjects like SQL Database, Access Database, QuickBooks, and Microsoft Excel. Loves to write on different technology and data recovery subjects on regular basis. Technology freak who always found exploring neo-tech subjects, when not writing, research is something that keeps her going in life.