Restore Sql Server Database with scripting

I’ve found this script which neatly restores an sql server database, saving you having to manually restore and trying to close off all connections. Note you have to run this against the master database.Hopefully the contents make sense.

 

ALTER DATABASE TestDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE TestDB 
FROM DISK = ‘C:\TestDB.bak’
WITH MOVE ‘TestDB’ TO ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\TestDB.mdf’,
MOVE ‘TestDB_log’ TO ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\TestDB.ldf’

ALTER DATABASE TestDB SET MULTI_USER