Query to Restore a database from backup in MSSQL
Introduction
Restoring a database from a backup in Microsoft SQL Server may sometimes fail if the database is currently being used by active connections. In such situations, switching the database to SINGLE_USER mode before performing the restore operation can help resolve the issue successfully.
Prerequisites
- Access to Microsoft SQL Server
- Valid database backup file
- Administrative privileges on the SQL Server
Implementation
Query to Restore a Database from Backup in MSSQL
If you encounter issues while restoring a database from backup in MSSQL, execute the following query:
Use Master
Alter Database databasename
SET SINGLE_USER With ROLLBACK IMMEDIATE
RESTORE DATABASE databasename
FROM DISK = ‘backup location’
WITH REPLACE;
Alter database databasename
SET MULTI_USER;
This query forces all active connections to disconnect, restores the database from the specified backup location, and then switches the database back to multi-user mode.
Conclusion
By using SINGLE_USER mode with ROLLBACK IMMEDIATE, you can successfully restore databases in Microsoft SQL Server even when active connections are preventing the restore process.
