
A database snapshot is created with the CREATE DATABASE statement. A database snapshot provides a read-only, static view of a database, which can be useful for reporting, auditing, and data recovery purposes.
Here is an example of how you might create a database snapshot:
CREATE DATABASE Audit_Snapshot ON
(
NAME = logical_file_name,
FILENAME = 'os_file_name'
)
AS SNAPSHOT OF source_database_name;
In this example:
- logical_file_name is the logical name of the database file from the source database.
- os_file_name is the physical path where the snapshot file will be stored.
- source_database_name is the name of the database you want to create a snapshot of.
For instance, if you want to create a snapshot of a database named MyDatabase, you would replace logical_file_name, os_file_name, and source_database_name with the appropriate values.
A database snapshot before a risky change
The most useful job for a database snapshot is a quick safety net before a deployment or a large data fix. Find the logical file names first, then create one sparse file per data file:
-- Logical names of the data files
SELECT name, physical_name FROM sys.master_files
WHERE database_id = DB_ID(N'MyDatabase') AND type_desc = N'ROWS';
CREATE DATABASE MyDatabase_PreRelease ON
(
NAME = MyDatabase,
FILENAME = 'D:\SQLData\MyDatabase_PreRelease.ss'
)
AS SNAPSHOT OF MyDatabase;
Reverting to a database snapshot
If the change goes wrong, revert the whole database to the moment the snapshot was taken. Drop any other snapshots of the database first, because a revert needs only one to exist:
USE master;
RESTORE DATABASE MyDatabase FROM DATABASE_SNAPSHOT = 'MyDatabase_PreRelease';
When the change has gone well, drop the snapshot: DROP DATABASE MyDatabase_PreRelease;
Things to know about database snapshots
- A snapshot is not a backup. It depends on the source database, and if the source is damaged or lost, the snapshot goes with it.
- Each page that changes in the source is copied to the snapshot first, so the snapshot file grows and writes on the source get slower the longer it is kept.
- Snapshots are read-only and available in every edition from SQL Server 2016 SP1.
For the full reference, see Microsoft’s database snapshots documentation.
From my SQL Server DBA handbook.