Last active
August 29, 2015 14:04
-
-
Save ryanoboril/eab91860a92094ac166b to your computer and use it in GitHub Desktop.
Scripted DB restore of SQL Server database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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