forked from olahallengren/sql-server-maintenance-solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseBackup.sql
4106 lines (3548 loc) · 234 KB
/
DatabaseBackup.sql
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
USE master
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseBackup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseBackup] AS'
END
GO
ALTER PROCEDURE [dbo].[DatabaseBackup]
@Databases nvarchar(max) = NULL,
@Directory nvarchar(max) = NULL,
@BackupType nvarchar(max), -- new Type 'COPY_PENDING_MIRRORS' - see @MirrorWhenNotAvailable for details
@Verify nvarchar(max) = 'N', -- additional to Y and N you can now specify 'SKIP_MIRRORS' to verify the original backup but not the mirrors
-- (particularly usefull with @MirrorType = 'COPY' or 'COPY_LATER')
@CleanupTime int = NULL,
@CleanupMode nvarchar(max) = 'AFTER_BACKUP',
@CleanupUsesCMD CHAR(1) = 'N', -- when = Y it will use a xp_cmd_shell call instead of xp_delete_files, because xp_delete_files could be extremly slow
-- if you do frequent log backups, particularly on SQL 2008 R2 before CU11 (> 2 h runtime)
@Compress nvarchar(max) = NULL,
@CopyOnly nvarchar(max) = 'N',
@ChangeBackupType nvarchar(max) = 'N',
@BackupSoftware nvarchar(max) = NULL,
@CheckSum nvarchar(max) = 'N',
@BlockSize int = NULL,
@BufferCount int = NULL,
@MaxTransferSize int = NULL,
@NumberOfFiles int = NULL,
@CompressionLevel int = NULL,
@Description nvarchar(max) = NULL,
@Threads int = NULL,
@Throttle int = NULL,
@Encrypt nvarchar(max) = 'N',
@EncryptionAlgorithm nvarchar(max) = NULL,
@ServerCertificate nvarchar(max) = NULL,
@ServerAsymmetricKey nvarchar(max) = NULL,
@EncryptionKey nvarchar(max) = NULL,
@ReadWriteFileGroups nvarchar(max) = 'N',
@OverrideBackupPreference nvarchar(max) = 'N',
@NoRecovery nvarchar(max) = 'N',
@URL nvarchar(max) = NULL,
@Credential nvarchar(max) = NULL,
@MirrorDirectory nvarchar(max) = NULL,
@MirrorCleanupTime int = NULL,
@MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP',
@MirrorURL nvarchar(max) = NULL,
@MirrorDirectory2 nvarchar(max) = NULL,
@MirrorCleanupTime2 int = NULL,
@MirrorCleanupMode2 nvarchar(max) = 'AFTER_BACKUP',
@MirrorDirectory3 nvarchar(max) = NULL,
@MirrorCleanupTime3 int = NULL,
@MirrorCleanupMode3 nvarchar(max) = 'AFTER_BACKUP',
-- Behavior, if the mirrors are not available (e.g. because of restart)
-- 'ERROR' - the procedure / SQL Agent Job fails; no backup is done
-- 'SKIP' - the mirror will be ignored, backup will be done on main @Directory and other @MirrorDirectory (if more than one is specified)
-- 'COPY_LATER' - will COPY the backup file(s) from the @Directory to the mirror server as soon ther mirror is available again
-- This will be helpfull, if your mirror is another Server and will f.e. reboot after a windows update.
-- Limitations / Rules:
-- - per default it will copy the skipped files regardless of the Backup type. So - if your mirror is offline, while you are doing a FULL backup and comes online
-- again when your next LOG backup occurs, the LOG backup job will copy the full backup to the (original) mirror
-- (regardless, if the mirrors specified to the LOG backup are the same as the ones for the FULL backup)
-- - per default it will copy the files after the regular backup is done (so your LOG backup will be done intime, even if the COPY of the FULL backup takes 10 min)
-- - if you don't like this (e.g. because you do LOG Backups every minute), set @SkipPendingMirrorCopies to 'Y'
-- and create a new backup job with @BackupType = 'COPY_PENDING_MIRRORS' which will take no new backup but will copy all pendings
-- - it will not copy files older than @MirrorCleanupTime
-- - it will save the commands that will be used for the copy into the master.dbo.CommandLog table, even if @LogToTable is set to 'N'
-- - when a new record is inserted (because a mirror was not available or MirrorType = 'COPY_LATER') the CommandType will be 'PENDING_COPY',
-- IndexType the Mirror number (1-3), StartTime the time of the original backup and EndTime the StartTime + @MirrorCleanupTime
-- - when the copy was successfull EndTime will be set to the timestamp of the copy -> pending copies have an EndTime > GetDate()
-- - the Verify and Cleanup command (when CleanUpMode = AFTER_BACKUP) will be excecuted after the last file copy (per mirror)
@MirrorWhenNotAvailable NVARCHAR(max) = 'ERROR',
@MirrorWhenNotAvailable2 NVARCHAR(max) = 'ERROR',
@MirrorWhenNotAvailable3 NVARCHAR(max) = 'ERROR',
@MirrorType NVARCHAR(max) = 'DEFAULT', -- WHEN 'DEFAULT' it uses the MIRROR TO parameter on SQL Enterprise Editions (or when using an external backup software)
-- WHEN 'COPY' (or the backup runs without external software on a non Enterprise SQL Server) it makes a windows file copy of the original backup files
-- Caution: this mirror type is less secure than the DEFAULT, because there is a little chance that data on the backup @Directory are
-- altered / delete (by user or firmware or controller bug) between the original backup an the end of the copy process
-- WHEN 'COPY_LATER': creates an entry in the CommandLog table, which causes the next procedure call with @SkipPendingMirrorCopies = 'N'
-- or with @BackupType = 'COPY_PENDING_MIRRORS' to copy the files
-- This makes most sense, if your Mirror target is on a remote site and you want to "mirror" the files asynchron
-- (use @SkipPendingMirrorCopies = 'Y' on your regular backups and create an extra job with @BackupType = 'COPY_PENDING_MIRRORS')
@MirrorCopyCommand NVARCHAR(100) = 'ROBOCOPY', -- let you use COPY, XCOPY or ROBOCOPY for copying the files to the mirror;
-- This will be necessary when you have databases / backup directories / mirror directories
-- with very long filenames (e.g. some MS Sharepoint databases that have an UNID in the database name), because COPY fails when the
-- full file name (source or target) is longer than 256 characters
-- ROBOCOPY supports long pathes too and uses parameters to retry 3 times (every 30 seconds) when the copy fails
@XCOPYFileLetter VARCHAR(10) = NULL,-- must be specified, if @MirrorCopyCommand = 'XCOPY'. When you run 'xcopy c:\temp\file1.txt c:\temp\file2.txt' (c:\temp\file1.txt must exists)
-- XCOPY will ask you, if file2.txt is a (F)ile or (D)irectory. Sadly there is no parameter to skip this question when copying single file
-- (/I works only for multiple files) and the question / answer is translated in the OS language of the SQL Server.
-- So you have to specify the "answer letter" for the file-answere (e.g. "F" for English "File" or "D" for German "Datei")
-- Caution: if you specify an invalid letter (e.g. "X") the XCOPY statement will never finish -> Job hangs
-- ========
-- Hint: If some of your servers are German and some English, you could specify "FD" too (on the German servers it would ignore the
-- ===== wrong choice "F" and use the correct "D"; be aware that "DF" would not work, since it would answere "D(irectory)" to the English servers
@SkipPendingMirrorCopies NVARCHAR(max) = 'N',
@CleanUpStartTime TIME = NULL, -- When @CleanUpStartTime and @CleanUpEndTime are specified the delition of old backup files will be only executed,
@CleanUpEndTime TIME = NULL, -- when the procedure was called in this timeframe.
-- Reason: xp_deletefile can be very slow, if there are many files in the backup directory (e.g. because
-- LOG backups are taken every minute and cleaned up after 14 days -> 14 * 24 * 60 = 20160 files) and should be only
-- executed once per night to prevent delays in the main working time.
-- Hint: Set the @CleanUpEndTime as @CleanUpStartTime + regular backup interval to prevent multiple executions
@AvailabilityGroups nvarchar(max) = NULL,
@Updateability nvarchar(max) = 'ALL',
@AdaptiveCompression nvarchar(max) = NULL,
@ModificationLevel int = NULL,
@LogSizeSinceLastLogBackup int = NULL,
@TimeSinceLastLogBackup int = NULL,
@DataDomainBoostHost nvarchar(max) = NULL,
@DataDomainBoostUser nvarchar(max) = NULL,
@DataDomainBoostDevicePath nvarchar(max) = NULL,
@DataDomainBoostLockboxPath nvarchar(max) = NULL,
@DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}',
@AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}',
@FileName nvarchar(max) = '{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}',
@AvailabilityGroupFileName nvarchar(max) = '{ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}',
@FileExtensionFull nvarchar(max) = NULL,
@FileExtensionDiff nvarchar(max) = NULL,
@FileExtensionLog nvarchar(max) = NULL,
@Init nvarchar(max) = 'N',
@DatabaseOrder nvarchar(max) = NULL,
@DatabasesInParallel nvarchar(max) = 'N',
@LogToTable nvarchar(max) = 'N',
@Execute nvarchar(max) = 'Y'
AS
BEGIN
----------------------------------------------------------------------------------------------------
--// Source: https://ola.hallengren.com //--
--// License: https://ola.hallengren.com/license.html //--
--// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //--
--// Version: 2019-02-10 10:40:47 //--
----------------------------------------------------------------------------------------------------
SET NOCOUNT ON
DECLARE @StartMessage nvarchar(max)
DECLARE @EndMessage nvarchar(max)
DECLARE @DatabaseMessage nvarchar(max)
DECLARE @ErrorMessage nvarchar(max)
DECLARE @StartTime datetime
DECLARE @SchemaName nvarchar(max)
DECLARE @ObjectName nvarchar(max)
DECLARE @VersionTimestamp nvarchar(max)
DECLARE @Parameters nvarchar(max)
DECLARE @Version numeric(18,10)
DECLARE @HostPlatform nvarchar(max)
DECLARE @DirectorySeparator nvarchar(max)
DECLARE @AmazonRDS bit
DECLARE @Updated bit
DECLARE @Cluster nvarchar(max)
DECLARE @DefaultDirectory nvarchar(4000)
DECLARE @QueueID int
DECLARE @QueueStartTime datetime
DECLARE @CurrentRootDirectoryID int
DECLARE @CurrentRootDirectoryPath nvarchar(4000)
DECLARE @CurrentDBID int
DECLARE @CurrentDatabaseID int
DECLARE @CurrentDatabaseName nvarchar(max)
DECLARE @CurrentBackupType nvarchar(max)
DECLARE @CurrentFileExtension nvarchar(max)
DECLARE @CurrentFileNumber int
DECLARE @CurrentDifferentialBaseLSN numeric(25,0)
DECLARE @CurrentDifferentialBaseIsSnapshot bit
DECLARE @CurrentLogLSN numeric(25,0)
DECLARE @CurrentLatestBackup datetime
DECLARE @CurrentDatabaseNameFS nvarchar(max)
DECLARE @CurrentDirectoryStructure nvarchar(max)
DECLARE @CurrentDatabaseFileName nvarchar(max)
DECLARE @CurrentMaxFilePathLength nvarchar(max)
DECLARE @CurrentFileName nvarchar(max)
DECLARE @CurrentDirectoryID int
DECLARE @CurrentDirectoryPath nvarchar(4000) -- changed from max to 4k because used as parameter to xp_fileexist
DECLARE @CurrentFilePath nvarchar(4000) -- changed from max to 4k because used as parameter to xp_fileexist
DECLARE @CurrentDate datetime
DECLARE @CurrentCleanupDate datetime
DECLARE @CurrentIsDatabaseAccessible bit
DECLARE @CurrentAvailabilityGroup nvarchar(max)
DECLARE @CurrentAvailabilityGroupRole nvarchar(max)
DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max)
DECLARE @CurrentIsPreferredBackupReplica bit
DECLARE @CurrentDatabaseMirroringRole nvarchar(max)
DECLARE @CurrentLogShippingRole nvarchar(max)
DECLARE @CurrentIsEncrypted bit
DECLARE @CurrentIsReadOnly bit
DECLARE @CurrentBackupSetID int
--DECLARE @CurrentIsMirror bit -- replaced by @CurrentMirror
DECLARE @CurrentMirror SMALLINT -- added
DECLARE @CurrentLastLogBackup datetime
DECLARE @CurrentLogSizeSinceLastLogBackup float
DECLARE @CurrentAllocatedExtentPageCount bigint
DECLARE @CurrentModifiedExtentPageCount bigint
DECLARE @CurrentCommand01 nvarchar(max)
DECLARE @CurrentCommand02 nvarchar(max)
DECLARE @CurrentCommand03 nvarchar(max)
DECLARE @CurrentCommand04 nvarchar(max)
DECLARE @CurrentCommand05 nvarchar(max)
DECLARE @CurrentCommand06 nvarchar(max)
DECLARE @CurrentCommand07 nvarchar(max)
DECLARE @CurrentCommand08 nvarchar(max)
DECLARE @CurrentCommand09 nvarchar(max)
DECLARE @CurrentCommandOutput01 int
DECLARE @CurrentCommandOutput02 int
DECLARE @CurrentCommandOutput03 int
DECLARE @CurrentCommandOutput04 int
DECLARE @CurrentCommandOutput05 int
DECLARE @CurrentCommandOutput08 int
DECLARE @CurrentCommandOutput09 int
DECLARE @CurrentCommandType01 nvarchar(max)
DECLARE @CurrentCommandType02 nvarchar(max)
DECLARE @CurrentCommandType03 nvarchar(max)
DECLARE @CurrentCommandType04 nvarchar(max)
DECLARE @CurrentCommandType05 nvarchar(max)
DECLARE @CurrentCommandType08 nvarchar(max)
DECLARE @CurrentCommandType09 nvarchar(max)
DECLARE @CurrentCommandLogId int
DECLARE @CommandLogIdAtStart INT -- the highest master.dbo.CommandLog.ID at the start (to prevent that pending copies that where created in the current session are copied to the mirrors)
DECLARE @cmd NVARCHAR(4000); -- used for direct xp_cmd_shell call (to get a list of backup files)
DECLARE @Template NVARCHAR(4000);
DECLARE @CurrentExtendedInfo XML
DECLARE @Directories TABLE (ID int PRIMARY KEY,
DirectoryPath nvarchar(max),
Mirror SMALLINT, -- changed from bit to SMALLINT
Completed BIT,
Available BIT DEFAULT 1)
DECLARE @URLs TABLE (ID int PRIMARY KEY,
DirectoryPath nvarchar(max),
Mirror bit)
DECLARE @DirectoryInfo TABLE (FileExists bit,
FileIsADirectory bit,
ParentDirectoryExists bit)
DECLARE @tmpDatabases TABLE (ID int IDENTITY,
DatabaseName nvarchar(max),
DatabaseNameFS nvarchar(max),
DatabaseType nvarchar(max),
AvailabilityGroup bit,
StartPosition int,
DatabaseSize bigint,
LogSizeSinceLastLogBackup float,
[Order] int,
Selected bit,
Completed bit,
PRIMARY KEY(Selected, Completed, [Order], ID))
DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY,
AvailabilityGroupName nvarchar(max),
StartPosition int,
Selected bit)
DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max),
AvailabilityGroupName nvarchar(max))
DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max),
DatabaseType nvarchar(max),
AvailabilityGroup nvarchar(max),
StartPosition int,
Selected bit)
DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max),
StartPosition int,
Selected bit)
DECLARE @CurrentBackupSet TABLE (ID int IDENTITY PRIMARY KEY,
Mirror SMALLINT,
VerifyCompleted bit,
VerifyOutput int)
DECLARE @CurrentDirectories TABLE (ID int PRIMARY KEY,
DirectoryPath nvarchar(max),
Mirror SMALLINT,
DirectoryNumber int,
CleanupDate datetime,
CleanupMode nvarchar(max),
CreateCompleted bit,
CleanupCompleted bit,
CreateOutput int,
CleanupOutput int)
DECLARE @CurrentURLs TABLE (ID int PRIMARY KEY,
DirectoryPath nvarchar(max),
Mirror bit,
DirectoryNumber int)
DECLARE @CurrentFiles TABLE ([Type] nvarchar(max),
FilePath nvarchar(max),
Mirror SMALLINT,
FileNumber SMALLINT)
DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime, Mirror SMALLINT)
-- added for faster Cleanup when @CleanupUsesCMD = 1
-- must not be a table variable because of bad execution plan (no statistics) leading to poor performance
CREATE TABLE #CleanUpFiles (FileWithPath NVARCHAR(2048),
CharBackupTime AS RIGHT(LEFT(FileWithPath, LEN(FileWithPath) - CHARINDEX('.', REVERSE(FileWithPath)) ), 15),
ShouldBeDeleted TINYINT NOT NULL DEFAULT 0
);
CREATE CLUSTERED INDEX #CleanUpFiles_ix ON #CleanUpFiles (CharBackupTime);
DECLARE @DirectoryCheck bit
DECLARE @Error int
DECLARE @ReturnCode int
DECLARE @EmptyLine nvarchar(max)
SET @Error = 0
SET @ReturnCode = 0
SET @EmptyLine = CHAR(9)
SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10))
IF @Version >= 14
BEGIN
SELECT @HostPlatform = host_platform
FROM sys.dm_os_host_info
END
ELSE
BEGIN
SET @HostPlatform = 'Windows'
END
SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END
----------------------------------------------------------------------------------------------------
--// Log initial information //--
----------------------------------------------------------------------------------------------------
SET @StartTime = GETDATE()
SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID)
SET @ObjectName = OBJECT_NAME(@@PROCID)
SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19)
SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @CleanupUsesCMD = ' + ISNULL('''' + REPLACE(@CleanupUsesCMD,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @CleanUpStartTime = ' + ISNULL(CAST(@CleanUpStartTime AS NVARCHAR(20)),'NULL')
SET @Parameters = @Parameters + ', @CleanUpEndTime = ' + ISNULL(CAST(@CleanUpEndTime AS NVARCHAR(20)),'NULL')
SET @Parameters = @Parameters + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorWhenNotAvailable = ' + ISNULL('''' + REPLACE(@MirrorWhenNotAvailable,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorDirectory2 = ' + ISNULL('''' + REPLACE(@MirrorDirectory2,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupTime2 = ' + ISNULL(CAST(@MirrorCleanupTime2 AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupMode2 = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode2,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorWhenNotAvailable2 = ' + ISNULL('''' + REPLACE(@MirrorWhenNotAvailable2,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorDirectory3 = ' + ISNULL('''' + REPLACE(@MirrorDirectory3,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupTime3 = ' + ISNULL(CAST(@MirrorCleanupTime3 AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @MirrorCleanupMode3 = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode3,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorWhenNotAvailable3 = ' + ISNULL('''' + REPLACE(@MirrorWhenNotAvailable3,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorType = ' + ISNULL('''' + REPLACE(@MirrorType,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @SkipPendingMirrorCopies = ' + ISNULL('''' + REPLACE(@SkipPendingMirrorCopies,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @SkipPendingMirrorCopies = ' + ISNULL('''' + REPLACE(@SkipPendingMirrorCopies,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @MirrorCopyCommand = ' + ISNULL('''' + REPLACE(@MirrorCopyCommand,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @XCOPYFileLetter = ' + ISNULL('''' + REPLACE(@XCOPYFileLetter,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL')
SET @Parameters = @Parameters + ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL')
SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL')
-- block added - set @MirrorType to COPY when using native mirror backups on a non Enterprise Edition
IF (@MirrorDirectory IS NOT NULL OR @MirrorDirectory2 IS NOT NULL OR @MirrorDirectory3 IS NOT NULL)
AND SERVERPROPERTY('EngineEdition') <> 3 -- no Enterprise / Dev / Evaluation edition
AND @MirrorType NOT LIKE 'COPY%'
AND @BackupSoftware IS NULL -- all three external backup tools supports mirrored backups on any SQL Server edition
BEGIN
SET @MirrorType = 'COPY'
SET @Parameters = @Parameters + '@MirrorType changed to ''COPY'' because mirrored backups are an Enterprise only feature.' + CHAR(13) + CHAR(10)
END
SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120)
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max))
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Platform: ' + @HostPlatform
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName)
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Parameters: ' + @Parameters
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Version: ' + @VersionTimestamp
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
SET @StartMessage = 'Source: https://ola.hallengren.com'
RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
----------------------------------------------------------------------------------------------------
--// Check core requirements //--
----------------------------------------------------------------------------------------------------
IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90
BEGIN
SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1
BEGIN
SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1
BEGIN
SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute')
BEGIN
SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%')
BEGIN
SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF ( @LogToTable = 'Y'
OR 'COPY_LATER' IN (@MirrorWhenNotAvailable, @MirrorWhenNotAvailable2, @MirrorWhenNotAvailable3, @MirrorType)
OR @BackupType = 'COPY_PENDING_MIRRORS'
)
AND NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'U' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandLog')
BEGIN
SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF @DatabasesInParallel = 'Y' AND NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'U' AND schemas.[name] = 'dbo' AND objects.[name] = 'Queue')
BEGIN
SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF @DatabasesInParallel = 'Y' AND NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'U' AND schemas.[name] = 'dbo' AND objects.[name] = 'QueueDatabase')
BEGIN
SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF @@TRANCOUNT <> 0
BEGIN
SET @ErrorMessage = 'The transaction count is not 0.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF @AmazonRDS = 1
BEGIN
SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF @Error <> 0
BEGIN
SET @ReturnCode = @Error
GOTO Logging
END
-- get initial CommandLog.ID
IF ( 'COPY_LATER' IN (@MirrorWhenNotAvailable, @MirrorWhenNotAvailable2, @MirrorWhenNotAvailable3, @MirrorType)
OR @BackupType = 'COPY_PENDING_MIRRORS')
AND OBJECT_ID('master.dbo.CommandLog') IS NOT NULL
SET @CommandLogIdAtStart = ISNULL((SELECT MAX(id) FROM master.dbo.CommandLog AS cl), 0);
----------------------------------------------------------------------------------------------------
--// Select databases //--
----------------------------------------------------------------------------------------------------
SET @Databases = REPLACE(@Databases, CHAR(10), '')
SET @Databases = REPLACE(@Databases, CHAR(13), '')
WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',')
WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',')
SET @Databases = LTRIM(RTRIM(@Databases));
WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS
(
SELECT 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition,
SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem
WHERE @Databases IS NOT NULL
UNION ALL
SELECT CAST(EndPosition AS int) + 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition,
SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem
FROM Databases1
WHERE EndPosition < LEN(@Databases) + 1
),
Databases2 (DatabaseItem, StartPosition, Selected) AS
(
SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem,
StartPosition,
CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected
FROM Databases1
),
Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS
(
SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem,
CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType,
CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup,
StartPosition,
Selected
FROM Databases2
),
Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS
(
SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem,
DatabaseType,
AvailabilityGroup,
StartPosition,
Selected
FROM Databases3
)
INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected)
SELECT DatabaseName,
DatabaseType,
AvailabilityGroup,
StartPosition,
Selected
FROM Databases4
OPTION (MAXRECURSION 0)
IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1
BEGIN
INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected)
SELECT name AS AvailabilityGroupName,
0 AS Selected
FROM sys.availability_groups
INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName)
SELECT availability_databases_cluster.database_name, availability_groups.name
FROM sys.availability_databases_cluster availability_databases_cluster
INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id
END
INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed)
SELECT [name] AS DatabaseName,
RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS,
CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType,
NULL AS AvailabilityGroup,
0 AS [Order],
0 AS Selected,
0 AS Completed
FROM sys.databases
WHERE [name] <> 'tempdb'
AND source_database_id IS NULL
ORDER BY [name] ASC
UPDATE tmpDatabases
SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END
FROM @tmpDatabases tmpDatabases
UPDATE tmpDatabases
SET tmpDatabases.Selected = SelectedDatabases.Selected
FROM @tmpDatabases tmpDatabases
INNER JOIN @SelectedDatabases SelectedDatabases
ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]')
AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL)
AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL)
WHERE SelectedDatabases.Selected = 1
UPDATE tmpDatabases
SET tmpDatabases.Selected = SelectedDatabases.Selected
FROM @tmpDatabases tmpDatabases
INNER JOIN @SelectedDatabases SelectedDatabases
ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]')
AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL)
AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL)
WHERE SelectedDatabases.Selected = 0
UPDATE tmpDatabases
SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition
FROM @tmpDatabases tmpDatabases
INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition
FROM @tmpDatabases tmpDatabases
INNER JOIN @SelectedDatabases SelectedDatabases
ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]')
AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL)
AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL)
WHERE SelectedDatabases.Selected = 1
GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2
ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName
IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = ''))
BEGIN
SET @ErrorMessage = 'The value for the parameter @Databases is not supported.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
----------------------------------------------------------------------------------------------------
--// Select availability groups //--
----------------------------------------------------------------------------------------------------
IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1
BEGIN
SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '')
SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '')
WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',')
WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',')
SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups));
WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS
(
SELECT 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition,
SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem
WHERE @AvailabilityGroups IS NOT NULL
UNION ALL
SELECT CAST(EndPosition AS int) + 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition,
SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem
FROM AvailabilityGroups1
WHERE EndPosition < LEN(@AvailabilityGroups) + 1
),
AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS
(
SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem,
StartPosition,
CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected
FROM AvailabilityGroups1
),
AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS
(
SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem,
StartPosition,
Selected
FROM AvailabilityGroups2
),
AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS
(
SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem,
StartPosition,
Selected
FROM AvailabilityGroups3
)
INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected)
SELECT AvailabilityGroupName, StartPosition, Selected
FROM AvailabilityGroups4
OPTION (MAXRECURSION 0)
UPDATE tmpAvailabilityGroups
SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected
FROM @tmpAvailabilityGroups tmpAvailabilityGroups
INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups
ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]')
WHERE SelectedAvailabilityGroups.Selected = 1
UPDATE tmpAvailabilityGroups
SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected
FROM @tmpAvailabilityGroups tmpAvailabilityGroups
INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups
ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]')
WHERE SelectedAvailabilityGroups.Selected = 0
UPDATE tmpAvailabilityGroups
SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition
FROM @tmpAvailabilityGroups tmpAvailabilityGroups
INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition
FROM @tmpAvailabilityGroups tmpAvailabilityGroups
INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups
ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]')
WHERE SelectedAvailabilityGroups.Selected = 1
GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2
ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName
UPDATE tmpDatabases
SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition,
tmpDatabases.Selected = 1
FROM @tmpDatabases tmpDatabases
INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName
INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName
WHERE tmpAvailabilityGroups.Selected = 1
END
IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0)
BEGIN
SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF (@Databases IS NULL AND @AvailabilityGroups IS NULL)
BEGIN
SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL)
BEGIN
SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
----------------------------------------------------------------------------------------------------
--// Check database names //--
----------------------------------------------------------------------------------------------------
SET @ErrorMessage = ''
SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', '
FROM @tmpDatabases
WHERE Selected = 1
AND DatabaseNameFS = ''
ORDER BY DatabaseName ASC
IF @@ROWCOUNT > 0
BEGIN
SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
SET @ErrorMessage = ''
SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', '
FROM @tmpDatabases
WHERE UPPER(DatabaseNameFS) IN(SELECT UPPER(DatabaseNameFS) FROM @tmpDatabases GROUP BY UPPER(DatabaseNameFS) HAVING COUNT(*) > 1)
AND UPPER(DatabaseNameFS) IN(SELECT UPPER(DatabaseNameFS) FROM @tmpDatabases WHERE Selected = 1)
AND DatabaseNameFS <> ''
ORDER BY DatabaseName ASC
OPTION (RECOMPILE)
IF @@ROWCOUNT > 0
BEGIN
SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.'
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
END
----------------------------------------------------------------------------------------------------
--// Select directories //--
----------------------------------------------------------------------------------------------------
-- tfranz: Routine replaced to prevent 4 times nearly equal code (beside the directory parameter)
-- the main directory (Default from Registry, when NULL) and up to three MirrorDirectories will now inserted with one statement
--
IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)
BEGIN
EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT;
END
IF @DefaultDirectory LIKE 'http://%' OR @DefaultDirectory LIKE 'https://%'
BEGIN
SET @URL = @DefaultDirectory
END
;
WITH WrkDirs AS (SELECT LTRIM(RTRIM(REPLACE(REPLACE(WrkDirectory, ', ', ','), ' ,', ','))) AS WrkDirectory, -- remove "formating spaces"
MirrorNo
FROM (VALUES (CASE WHEN @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux'
THEN '.'
WHEN @Directory IS NOT NULL
THEN @Directory
WHEN @DefaultDirectory IS NOT NULL AND @URL IS NULL -- @DefaultDirectory contains an URL
THEN @DefaultDirectory
END, 0),
(@MirrorDirectory, 1),
(@MirrorDirectory2, 2),
(@MirrorDirectory3, 3)
) m(WrkDirectory, MirrorNo)
),
Directories (StartPosition, EndPosition, Directory, WrkDirectory, MirrorNo) AS
( -- Split the directories, if backup goes to several target disks
SELECT 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', WrkDirectory, 1), 0), LEN(WrkDirectory) + 1) AS EndPosition,
SUBSTRING(WrkDirectory, 1, ISNULL(NULLIF(CHARINDEX(',', WrkDirectory, 1), 0), LEN(WrkDirectory) + 1) - 1) AS Directory,
WrkDirectory,
MirrorNo
FROM WrkDirs
WHERE WrkDirectory IS NOT NULL
UNION ALL
SELECT CAST(EndPosition AS int) + 1 AS StartPosition,
ISNULL(NULLIF(CHARINDEX(',', WrkDirectory, EndPosition + 1), 0), LEN(WrkDirectory) + 1) AS EndPosition,
SUBSTRING(WrkDirectory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', WrkDirectory, EndPosition + 1), 0), LEN(WrkDirectory) + 1) - EndPosition - 1) AS Directory,
WrkDirectory,
MirrorNo
FROM Directories
WHERE EndPosition < LEN(WrkDirectory) + 1
)
INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed)
SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID,
Directory,
MirrorNo,
0
FROM Directories
OPTION (MAXRECURSION 0)
;
----------------------------------------------------------------------------------------------------
--// Check directories //--
----------------------------------------------------------------------------------------------------
SET @DirectoryCheck = 1
-- tfranz: redesigned for more specific error messages; use the same checks for all Directory parameters
SET @ErrorMessage = NULL;
SELECT @ErrorMessage =
ISNULL(N'The value for the parameter '
+ STUFF((SELECT DISTINCT N'/' + CASE Mirror WHEN 0 THEN N'@Directory' WHEN 1 THEN N'@MirrorDirectory' WHEN 2 THEN N'@MirrorDirectory2' WHEN 3 THEN N'@MirrorDirectory3' END
FROM @Directories
WHERE (NOT (DirectoryPath LIKE N'_:' OR DirectoryPath LIKE N'_:\%' OR DirectoryPath LIKE N'\\%\%')) -- no valid path format (drive, local path or UNC path)
OR DirectoryPath LIKE N'__%:%' -- colon (':') after the second character
OR NULLIF(LTRIM(DirectoryPath), N'') IS NULL -- empty path specified
FOR XML PATH('i'), root('c'), type
).query('/c/i').value(N'.', 'nvarchar(4000)') , 1, 1, N'')
+ N' is not supported.' + CHAR(13) + CHAR(10), N'')
+ CASE WHEN (SELECT COUNT(*) FROM (SELECT DISTINCT COUNT(*) num FROM @Directories AS d GROUP BY d.Mirror) sub) > 1
THEN N'The number of comma separated target directories in the parameters @Directory, @MirrorDirectory, @MirrorDirectory2 and @MirrorDirectory3 must be the same if the parameter is not NULL.' + CHAR(13) + CHAR(10)
ELSE N''
END
+ CASE WHEN EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1)
THEN N'The same directory was multiple times defined in @Directory / @MirrorDirectory / @MirrorDirectory2 / @MirrorDirectory3' + CHAR(13) + CHAR(10)
ELSE N''
END
+ CASE WHEN @BackupSoftware NOT IN('SQLBACKUP','SQLSAFE')
THEN N'' -- just for performance (no SELECT if other software is used)
WHEN @BackupSoftware IN('SQLBACKUP','SQLSAFE')
AND (SELECT MAX(number) FROM (SELECT d2.Mirror, COUNT(*) AS number FROM @Directories AS d2 WHERE d2.Mirror > 0 GROUP BY d2.Mirror) AS sub) > 1
AND @MirrorType = 'DEFAULT'
THEN N'Your backup software ' + @BackupSoftware + N' does not support Backup Mirroring to multiple target directories.' + CHAR(13) + CHAR(10)
ELSE N''
END
+ CASE WHEN @BackupSoftware = 'SQLSAFE'
AND @MirrorDirectory3 IS NOT NULL -- see http://community.idera.com/forums/topic/backup-mirroring/
AND @MirrorType = 'DEFAULT'
THEN N'Idera SQL Safe supports only two mirror directories. Please remove the @MirrorDirectory3 parameter or set @MirrorType to ''COPY''.' + CHAR(13) + CHAR(10)
ELSE N''
END
+ N' '
-- removed: check for Enterprise Edition when mirroring is used, because the external backup tools supports mirroring in any SQL Editions
-- and when it is not Enterprise it will copy the backup files manual to the mirror target(s)
IF NULLIF(@ErrorMessage, N'') IS NOT NULL
BEGIN
RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT
SET @Error = @@ERROR
RAISERROR(@EmptyLine,10,1) WITH NOWAIT
SET @DirectoryCheck = 0
END
-- check for enabled xp_cmd used for Fake-Mirroring for native SQL Backups on non-Enterprise servers
-- (by copying the backup files) or @CleanupUsesCMD
IF ( @MirrorType LIKE 'COPY%'
AND (@MirrorDirectory IS NOT NULL OR @MirrorDirectory2 IS NOT NULL OR @MirrorDirectory3 IS NOT NULL)
)
OR @CleanupUsesCMD = 'Y'
BEGIN
SET @ErrorMessage = NULL
IF (SELECT CONVERT(BIT, value_in_use) FROM sys.configurations WHERE name = 'xp_cmdshell') = 0
-- commented out, because - without SA - you usually have no select privilege on sys.credentials
--OR ( IS_SRVROLEMEMBER('sysadmin') = 0
-- AND NOT EXISTS (SELECT * FROM sys.credentials AS c WHERE name = '##xp_cmdshell_proxy_account##')
-- )
BEGIN
IF @CleanupUsesCMD = 'Y'
SET @ErrorMessage = 'To use the CMD-Mode for backup cleanups (@CleanupUsesCMD = ''Y'') the sys configuration xp_cmdshell has to been enabled.'
ELSE
SET @ErrorMessage = '@MirrorType is set to ''COPY'' (manual or automatic, if a @MirrorDirectory is specified but the procedure runs on a non-Enterprise edition (without MIRROR TO-support) and not using an external @BackupSoftware). ' + CHAR(13) + CHAR(10)
+ 'To use the copy mirroring (file copy after backup) the sys configuration xp_cmdshell has to been enabled. '
;
SET @ErrorMessage = @ErrorMessage + CHAR(13) + CHAR(10)
+ 'When the backup runs from an account without sysadmin privilege a xp_cmdshell_proxy_account must be specified (using sp_xp_cmdshell_proxy_account) ' + CHAR(13) + CHAR(10)
+ 'which needs read rights to the @Directory and write / delete rights to each @MirrorDirectory' + CHAR(13) + CHAR(10) + ' '
RAISERROR(@ErrorMessage,16,1) WITH NOWAIT
SET @Error = @@ERROR
SET @DirectoryCheck = 0
END
IF @MirrorType = 'COPY_LATER'
UPDATE @Directories SET Mirror = Mirror * -1 WHERE Mirror > 0 -- negate mirror number -> the copy command will be pasted into the command log instead of being executed
END
IF @DirectoryCheck = 1
BEGIN
WHILE (1 = 1)
BEGIN
SELECT TOP 1 @CurrentRootDirectoryID = ID,
@CurrentRootDirectoryPath = DirectoryPath,
@CurrentMirror = ABS(Mirror)
FROM @Directories
WHERE Completed = 0
ORDER BY ID ASC
IF @@ROWCOUNT = 0
BEGIN
BREAK
END