Skip to content

Instantly share code, notes, and snippets.

@ryanoboril
Last active August 29, 2015 14:04
Show Gist options
  • Save ryanoboril/eab91860a92094ac166b to your computer and use it in GitHub Desktop.
Save ryanoboril/eab91860a92094ac166b to your computer and use it in GitHub Desktop.
Scripted DB restore of SQL Server database
-- TODO Parameterize me!
RESTORE FILELISTONLY
FROM DISK = 'C:\dbname-snapshot-20140410.bak'
GO
-- Put database in single-user mode.
-- This will also close existing connections.
ALTER DATABASE dbName
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
-- Drop old database.
DROP DATABASE dbName;
-- Restore database from .bak file.
-- Bak file name can be whatever, otherwise replace
-- 'dbName' with name of database.
RESTORE DATABASE dbName
FROM DISK = 'C:\dbname-snapshot-20140410.bak'
WITH MOVE 'dbName_Data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\dbName_Data.mdf',
MOVE 'dbName_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\dbName_Log.ldf'
-- Create a login with the same name as the database username (from provided credentials).
-- Then map that to a restored database user.
USE dbName;
DROP USER dbUsername;
GO
CREATE USER [dbUsername] FOR LOGIN [dbUsername]
GO
ALTER USER [dbUsername] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', N'dbUsername'
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment