forked from bulentgucuk/DBA-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCreate Dynamic Database SnapShot Daily.sql
More file actions
52 lines (41 loc) · 1.31 KB
/
Create Dynamic Database SnapShot Daily.sql
File metadata and controls
52 lines (41 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
----------------------------------------------------------
-- Create Snapshot of a Source database in the same folder
----------------------------------------------------------
SET NOCOUNT ON;
DECLARE @SourceDBName SYSNAME,
@SnapShotDBName SYSNAME,
@InitRowId INT,
@MaxRowId INT,
@SqlCmd NVARCHAR(MAX)
SELECT @SourceDBName = DB_NAME()
SELECT @SnapShotDBName = @SourceDBName + '_SnapShot_' + CONVERT(VARCHAR(10), GETDATE(), 112)
SELECT @InitRowId = 1,
@SqlCmd = ''
DECLARE @T TABLE (
RowId INT IDENTITY (1,1),
Name VARCHAR(256),
FileName VARCHAR(512)
)
INSERT INTO @T (Name, FileName)
SELECT '(name = ' + name + ',' ,
'Filename = ''' + REPLACE(REPLACE(physical_name, '.mdf','.SS'),'.ndf','.SS') + '''),'
FROM sys.database_files
WHERE type = 0
-- Get the max row to loop
SELECT @MaxRowId = MAX(RowId)
FROM @T
-- Remove the comma at the last file for command to execute
UPDATE @T
SET FileName = REPLACE([FileName], ',' , '')
WHERE RowId = @MaxRowId
-- Build SQL Command to be executed
WHILE @InitRowId <= @MaxRowId
BEGIN
SELECT @SqlCmd = @SqlCmd + Name + [FileName] + CHAR(13)
FROM @T
WHERE RowId = @InitRowId;
SELECT @InitRowId = @InitRowId + 1;
END
SELECT @SqlCmd = 'CREATE DATABASE ' + @SnapShotDBName + ' ON ' + CHAR(13)+@SqlCmd + 'AS SNAPSHOT OF ' + @SourceDBName + ';'
PRINT @SqlCmd;
EXEC (@SqlCmd);