Tuesday, July 9, 2013

Restoring an SQL Server Database that is in use

Often we have to restore a database in sql server but that is in use.  The script below enables restore of database even if it is use. 


Adjust for your needs and use at your own risk.


USE [master]
GO
if exists (select * from sysdatabases where name='MY_DATABASE') begin
print 'taking database MY_DATABASE to single mode'
ALTER DATABASE MY_DATABASE SET SINGLE_USER WITH ROLLBACK IMMEDIATE
end
GO
if exists (select * from sysdatabases where name='MY_DATABASE')
begin
print 'drop MY_DATABASE'
DROP DATABASE MY_DATABASE
end
go
USE [master]
GO
RESTORE DATABASE MY_DATABASE FROM
DISK = N'C:\MSSQL\Backup\MY_DATABASE_backup.bak' WITH FILE = 1,
MOVE N'DataTemplateSQL_dat' TO N'c:\MSSQL\DATA\MY_DATABASE.mdf',
MOVE N'DataTemplateSQL_log' TO N'c:\MSSQL\DATA\MY_DATABASE.LDF',
NOUNLOAD, STATS = 10
GO
use MY_DATABASE
go

No comments:

Post a Comment