Перейти к содержимому

Как открыть бэкап базы sql

  • автор:

Восстановление резервной копии базы данных
(среда SQL Server Management Studio)

В данной статье подробно рассмотрим процесс восстановления полной резервной копии базы данных с использованием среды SQL Server Management Studio.

Введите адрес сервера или его псевдоним и данные для авторизации.
Нажмите «Соединить».

podkljuchites-ms-sql-server

В Обозревателе объектов разверните дерево сервера, нажав на имени сервера. Раскройте узел «Базы данных» и выберите из раскрывающегося списка базу данных для восстановления, нажмите по ней правой кнопкой мыши и в появившемся контекстном меню выберите «Задачи» — команду «Восстановить» — «База данных…».

Запустится Мастер восстановления базы данных.
Чтобы указать источник и расположение восстанавливаемых резервных наборов данных, выберите вариант «Устройство».

Нажмите на кнопку обзора (…), после чего откроется диалоговое окно «Выберите устройство резервного копирования». В поле «Тип носителя резервной копии» в раскрывающемся списке выберите «Файлы». Нажмите кнопку «Добавить» и укажите носитель и расположение резервной копии для восстановления.

После добавления устройства в список «Расположение резервной копии» нажмите «OK» для возвращения на вкладку «Общие».

В разделе «Назначение», в поле «База данных» автоматически появится имя базы данных для восстановления. Если потребуется изменить имя базы данных, просто введите новое имя в окно «База данных».

В поле «Восстановить в» оставьте значение по умолчанию «Последняя созданная резервная копия».

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

Переходим во вкладку «Файлы», на панели «Выбор страницы» нажмите на диалоговое окно «Файлы».
При необходимости здесь можно восстановить базу данных в новое расположение, определив новое место восстановления для каждого файла в сетке «Восстановить файлы базы данных как».

Для просмотра или выбора дополнительных параметров нажмите на вкладку «Параметры» на панели «Выбор страницы». При необходимости здесь можно указать любые из следующих параметров, подходящих к ситуации:

  • переписать существующую базу данных;
  • сохранить настройки репликации;
  • ограничить доступ к восстановленной базе данных.

Установив все необходимые параметры, нажмите кнопку «ОК». Запустится процесс восстановления базы данных.

После того, как процесс по восстановлению будет завершен увидим уведомление «Восстановление базы данных успешно завершено».

PROИТ

Office 365, AD, Active Directory, Sharepoint, C#, Powershell. Технические статьи и заметки.

SQL Server Как восстановить базу данных из bak файла бэкапа (restore DB from backup)

Задача: восстановить базу данных из файла бэкапа.
Шаг за шагом с иллюстрациями рассмотрим как это сделать на примере СУБД Microsoft SQL Server 2014. Кроме восстановления посмотрим также как сделать линковку (связь) пользователя базы данных и логина СУБД (будет использовать SQL скрипт sp_change_users_login).
Итак, залогиньтесь в СУБД SQL Server и в дереве в контекстном меню пункта Databases выберите пункт «Restore Database. «:

В параметрах выберем «Device» и перейдем по кнопке «Обзор» (кнопка с многоточием):

В открывшемся окне нажимаем «Add» и находим файл бэкапа базы данных:

Перед началом рекомендуется проверить корректность файла, нажав кнопку «Verify Backup Media«:

Далее перейдем в левом меню на раздел «Files» и проверим пути для сохранения восстановленной базы данных. При необходимости меняем их (не обязательно):

Также можно перейти в раздел «Options» и сделать настройки, если требуется (не обязательно):

Нажимаем ОК и дожидаемся сообщения об успешном восстановлении базы:

Если база данных содержала информацию о пользователях, то необходимо проверить их связь с логинами. Для этого в дереве находим вновь воссозданную БД, раскрываем пункт «Security» — «Users» и выбираем какого-либо существующего пользователя и в контекстном меню переходим на пункт «Properties«:

В открывшемся окне свойств пользователя мы видим, что пользователь существует только в контексте это базы (т.е. не связан ни с каким логином «SQL user without login»):

Это не позволит Вам подключиться к базе данных под данным пользователем. Поэтому создадим логин для этого пользователя (если логин уже существует, пропустите этот шаг). В дереве объектов СУБД перейдем на уровень выше (выше, чем текущая БД) в пункт «Security» и в контекстном меню пункта «Logins» выберем «New Login. «:

В открывшемся окне заполняем:
— login name — имя логина (я всегда делаю его одноименным с пользователем базы)
— выбираем параметр «SQL Server authentication» и задаем пароль
— снимаем «галку» «Enforce password policy»
— default database — прописываем нужную базу данных:

Далее можно перейти в левом меню в раздел «User Mapping«, где увидим, что можно закрепить за созданным логином некого пользователя в базе. Если у Вас база данных не содержит никаких пользователей, то задайте эти параметры, как показано на рисунке (в противном случае пропустите этот шаг) и будет автоматически создан пользователь БД связанный с данным логином:

При этом логин будет создан, но не связан с пользователем.

Чтобы связать логин СУБД с пользователем конкретной базы данных выполним следующий SQL-скрипт:

Теперь, если снова перейти в свойства пользователя БД, то мы видим, что пользователь связан с только что созданным логином.

Import .bak file to a database in SQL server

How can I import this date to a database in SQL Server?

alex's user avatar

9 Answers 9

On SQL Server Management Studio

  1. Right click Databases on left pane (Object Explorer)
  2. Click Restore Database.
  3. Choose Device, click . , and add your .bak file
  4. Click OK, then OK again

This will show you a list of database files contained in DB.bak:

You will need the logical names from that list for the MOVE operation in the second step:

and you have to move appropriate mdf,ndf & ldf files using

You can simply restore these database backup files using native SQL Server methods, or you can use ApexSQL Restore tool to quickly virtually attach the files and access them as fully restored databases.

Disclaimer: I work as a Product Support Engineer at ApexSQL

Instead of choosing Restore Database. select Restore Files and Filegroups.

Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.

(The SQL Server restore option names are not intuitive for what should a very simple task.)

On Microsoft SQL Server Management Studio 2019:

enter image description here

On Restore Database window:

Choose Add and pick target file

OK to confirm restore

enter image description here

  1. Connect to a server you want to store your DB
  2. Right-click Database
  3. Click Restore
  4. Choose the Device radio button under the source section
  5. Click Add.
  6. Navigate to the path where your .bak file is stored, select it and click OK
  7. Enter the destination of your DB
  8. Enter the name by which you want to store your DB
  9. Click OK

Yash Saraiya's user avatar

Although it is much easier to restore database using SSMS as stated in many answers. You can also restore Database using .bak with SQL server query, for example

In above Query you need to keep in mind about .mdf/.ldf file location. You might get error

System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)

So you need to run Query as below

Once you will run above Query you will get location of mdf/ldf use it Restore database using query

How to Restore Database in SQL Server from .Bak File Step By Step

  • author image

Written By Charanjeet Kaur linkdin

Approved By Raja Jegan R linkdin

Updated on March 13, 2023

Min Reading 8 Min

Summary: This article will describe step-by-step process to restore database in SQL Server from .bak file. You can try restoring the backup file by using SQL Server Management Studio (SSMS), executing Transact-SQL (T-SQL) query, or with PowerShell command. If backup isn’t available or is obsolete, or the database is corrupt, Stellar repair for MSSQL — Technician software can come in handy. The technician comprises tools to resolve SQL Server database issues without prolonged downtime. The tools can be used to recover data from corrupted backup, repair a corrupted SQL database file (.mdf/.ndf), and reset password of a database file.

Free Download For Windows

Free Download For Windows

Many SQL Server Database Administrators (DBAs) struggle repeatedly with errors like abrupt termination, database connection or transient errors, problem with drivers, malicious software attack, etc. Such errors can render a database unusable. While rebooting the SQL server may resolve the problem in some cases, using a backup (.bak) file is the most feasible option to restore SQL database (db).

Restore Database in SQL Server from .BAK File

SQL Server database restoration is performed for Full, Differential, File or Filegroup database backup with the help of SQL Server Management Studio (SSMS), T-SQL, or by using PowerShell .

Things You Need to Know Before Backup Restoration

Before you proceed with the backup restoration process, you will need to:

  • Close all the active connections before attempting to restore SQL Server database from .BAK file. Doing so will prevent the restore process from failing due to active database connections.
  • Backups that are created on recent SQL Server versions cannot be restored to earlier versions of SQL Server.
  • Backup the active transaction log, before performing the full database backup. This is because, if the active transaction log (also referred to as the tail of the log) becomes unavailable, all transactions in that log will be lost.
  • When you want to restore a db from another server instance, you will need to manage metadata to make the db available on another server. Refer to this link for more information.

Methods to Restore SQL Server Database from .BAK File

Method 1 – Restore SQL Database using SSMS

If you have SSMS installed on your system, follow these steps to restore your SQL database from the backup (.bak) file:

Step 1: Open SSMS and connect to an instance of SQL Server.

Step 2: Next, go to Object Explorer and click the Server Name to expand the Server tree.

Step 3: Navigate to Databases and open the database you want to restore in SQL Server.

Step 4: Right-click the Database , and then click Restore Database .

Figure 1 — Restore Database Option

Step 5: The Restore Database window is displayed. From the General page, under Source section, select any of these options:

a. Choose the Database option, and then select the database you want to restore from the drop-down list.

Note: When the backup is taken from another server, the destination server won’t contain the backup history information for the selected database. However, you can manually specify the database file or device by selecting the Device option.

b. Choose the Device option, and then click the ellipses (. ) to find your backup file.

  • From ‘Select backup devices’ window, choose File as backup media, and then click Add .
  • Locate and select the .BAK file you want to restore, and then click OK .
  • Again click OK to return to the Restore Database window.

Figure 2 — Locate SQL Database Backup File

  • From ‘Select backup devices’ window, choose File as backup media, and then click Add .

Figure 3 – Select Add to Navigate to .BAK File

  • Locate and select the .BAK file you want to restore, and then click OK .

Figure 4 – Select the Backup File

  • Again click OK to return to the ‘Restore Database’ window.

Figure 5 – Selected Backup File in Specify Backup Window

Step 6: The name of the database to be restored is displayed in the Database box under Destination section. And, information of the selected backup file will be added in the Backup sets to restore section.

Figure 6 – Backup File in Restore Database Window

All the information needed to restore the database from backup file has been entered. You just need to click on the OK button to restore the database. However, SQL .bak files store information about the location of data files, and in case of any problems with those files, such as conflicting data file names” or “the destination directory does not exist” can result in an error.

Such problems usually occur when restoring SQL database from a .BAK file created on another SQL Server installation. Changing the file settings from the Options page can help overcome any such problem. To do so, follow these steps:

a. Select Options under Select a Page .

Figure 7 — Locate SQL Database Backup File

b. On the Options page, do the following:

  • Under the Restore options section, select the ‘ Overwrite the existing database (WITH REPLACE) ’ option.

Figure 8 — Restore Options Section

  • Under the Recovery State section, choose ‘Leave the database ready to use by rolling back uncommitted transactions. Additional transaction logs cannot be restored.(RESTORE WITH RECOVERY)’. .

Figure 9 — Recovery state Options

Step 7: To proceed with the restore process, hit the OK button.

Step 8: The window with restore progress is displayed.

Figure 10 — Restore Process in Progress Window

Step 9: Click OK when the ‘restore of database completed successfully’ message pops up.

Figure 11 — Database Restoration Completed Message

Your SQL database will be successfully restored.

Method 2 – Restore sql server database from .bak file Using T-SQL

You may also use T-SQL query to restore a database from the .bak file by following these steps:

Step 1: Start SSMS , and then connect to an instance of SQL Server.

Step 2: Click the New Query option.

Step 3: In the Query Editor window, run any of the following RESTORE statement:

  • For restoring the entire database from the .bak file, use the following command:

Make sure to replace ‘DBName’ with the name of the database that you wish to restore. Also, replace ‘BackupFilePath’ with the path of your db backup file, and ‘BackupFileName’ with the name of your .bak file.

  • For restoring a specific file from the .bak file, use a command that resembles the following:

Replace ‘FileName’ with the name of the file you want to restore.

Method 3 – Restore-SQL Database with Replace PowerShell

You can also restore a SQL db by using the Restore-SqlDatabase cmdlet. The cmdlet performs restore operations including full database restores, transaction log, and database file restores on a SQL Server db.

IMPORTANT! If you have an updated full database backup file, you can efficiently restore the database by using the above methods. But, you cannot perform selective database recovery from the backup file. For instance, you can recover a single table (if needed) from backup.

What Else You Can Do to Restore SQL Server Database?

If your SQL database is corrupt and you don’t have a complete backup copy to restore the db, using Stellar repair for MSSQL- Technician can help. It’s a comprehensive software that comprises tools to help DBAs solve multiple problems. With the backup extractor tool available in the technician, you can extract data from a corrupted backup file (.bak). You can use the SQL repair tool to fix severely corrupted SQL data files (.mdf and .ndf) and recover all the database objects. In addition, the password recovery tool of the technician can help reset lost/forgotten password of a db file.

Conclusion

Maintaining databases in SQL Server and keeping them up and running is the foremost priority of DBAs. Thus, if there is any conflict, it should be resolved quickly by performing SQL server database restoration process using the last known good backup copy.

Understanding the T-SQL commands or steps to use SSMS to restore database in SQL Server from .bak file can help you carry out SQL database restoration efficiently. If the backup file is not available or you are unable to restore the db from the file, using the backup extractor tool of Stellar Repair for MS SQL- Technician software can help. The tool helps extract and recover data from a corrupted .bak file. You can also use other tools available in the technician to resolve database corruption and password recovery issues.

Q. Does the Stellar Repair for MS SQL software recover data from a corrupt .bak file?

A. No, the software helps repair a corrupt SQL database (MDF or NDF) file and restores data in a new file without making any changes to the original file.

You can try using the backup extractor tool available in Stellar Repair for MS SQL -Technician to extract data from a corrupted backup (.bak) file.

Q. Is it possible to restore a differential backup without having a full database backup?

A. No, it is not possible to restore SQL database from differential backup if you haven’t previously taken a full database backup. This is because a differential backup relies on the last full data backup, and saves only the data that has changed since the last full backup was performed.

Q. Is it possible to open a corrupt .bak file in SQL Server using command line?

A. We don’t recommend the use of command line as there are chances of data loss. You can try Stellar Repair for MS SQL-Technician to open a corrupt .bak file in SQL Server.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Car Rental HPN Inside the Terminal