-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy path05 Other Objects.sql
More file actions
2785 lines (2425 loc) · 83.6 KB
/
05 Other Objects.sql
File metadata and controls
2785 lines (2425 loc) · 83.6 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
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 DbaData
GO
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba'
AND r.ROUTINE_NAME = 'GetXESessionData_ErrorReported'
)
BEGIN
EXEC('CREATE PROC dba.GetXESessionData_ErrorReported AS PRINT CURRENT_TIMESTAMP;');
END;
GO
ALTER PROC dba.GetXESessionData_ErrorReported
/*
Purpose:
Returns Extended Events Session data.
Inputs: none.
History:
09/15/2016 DBA Created
*/
AS
BEGIN
--SPID included within session name for isolation.
DECLARE @XESessionName SYSNAME =
'Error Handling Session(SPID ' + CAST(@@SPID AS VARCHAR) + ')';
----<temp>
--INSERT INTO DbaData.dba.Debug([Message])
--VALUES('dba.GetXESessionData_ErrorReported @@SPID = ' + CAST(@@SPID AS VARCHAR));
----</temp>
IF NOT EXISTS(
SELECT *
FROM master.sys.server_event_sessions s
WHERE s.name = @XESessionName
)
BEGIN
DECLARE @ErrMsg NVARCHAR(MAX) = 'Session ' + @XESessionName + ' does not exist.';
RAISERROR(@ErrMsg, 16, 1);
RETURN;
END
DECLARE @XEData XML
SELECT @XEData = CAST(xet.target_data AS XML)
FROM sys.dm_xe_session_targets AS xet
JOIN sys.dm_xe_sessions AS xe
ON (xe.address = xet.event_session_address)
WHERE xe.name = @XESessionName;
/*
Check value of "totalEventsProcessed" to ensure events have been
dispatched to event session target (ring_buffer).
If no events have been processed, delay for a period > MAX_DISPATCH_LATENCY (in seconds).
*/
IF @XEData.value('(/RingBufferTarget/@totalEventsProcessed)[1]', 'INT') = 0
BEGIN
WAITFOR DELAY '00:00:02';
SELECT @XEData = CAST(xet.target_data AS XML)
FROM sys.dm_xe_session_targets AS xet
JOIN sys.dm_xe_sessions AS xe
ON (xe.address = xet.event_session_address)
WHERE xe.name = @XESessionName;
END
--SELECT signature must match the [dba].[ErrorReported] table type:
SELECT
x.c.value(N'(action[@name="session_id"]/value)[1]', N'SMALLINT') AS SessionId,
x.c.value(N'(@name)[1]', N'NVARCHAR(MAX)') AS EventName,
x.c.value(N'(@timestamp)[1]', N'datetime') AS EventTime,
x.c.value(N'(data[@name="error_number"]/value)[1]', N'INT') AS ErrorNumber,
x.c.value(N'(data[@name="severity"]/value)[1]', N'INT') AS Severity,
x.c.value(N'(data[@name="state"]/value)[1]', N'INT') AS [State],
x.c.value(N'(data[@name="user_defined"]/value)[1]', N'NVARCHAR(MAX)') AS UserDefined,
x.c.value(N'(data[@name="category"]/text)[1]', N'NVARCHAR(MAX)') AS Category,
x.c.value(N'(data[@name="destination"]/text)[1]', N'NVARCHAR(MAX)') AS Destination,
x.c.value(N'(data[@name="is_intercepted"]/value)[1]', N'NVARCHAR(MAX)') AS IsIntercepted,
x.c.value(N'(data[@name="message"]/value)[1]', N'NVARCHAR(MAX)') AS [Message],
x.c.value(N'(action[@name="sql_text"]/value)[1]', N'NVARCHAR(MAX)') AS SqlText
FROM @XEData.nodes('//RingBufferTarget/event') AS x(c)
END
GO
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba'
AND r.ROUTINE_NAME = 'DropXESession_ErrorReported'
)
BEGIN
EXEC('CREATE PROC dba.DropXESession_ErrorReported AS PRINT CURRENT_TIMESTAMP;');
END;
GO
ALTER PROC dba.DropXESession_ErrorReported
/*
Purpose:
Stops and drops an Extended Events Session that monitor errors.
Inputs: none.
History:
09/05/2016 DBA Created
08/07/2017 DBA Check session state before attempting to stop.
*/
AS
BEGIN
--SPID included within session name for isolation.
DECLARE @XESessionName SYSNAME =
'Error Handling Session(SPID ' + CAST(@@SPID AS VARCHAR) + ')';
----<temp>
--INSERT INTO DbaData.dba.Debug([Message])
--VALUES('dba.DropXESession_ErrorReported @@SPID = ' + CAST(@@SPID AS VARCHAR));
----</temp>
IF EXISTS (
SELECT *
FROM master.sys.dm_xe_sessions s
WHERE s.name = @XESessionName
AND s.create_time IS NOT NULL
)
BEGIN
EXEC('ALTER EVENT SESSION [' + @XESessionName + '] ON SERVER STATE=STOP;');
END
IF EXISTS(
SELECT *
FROM master.sys.server_event_sessions s
WHERE s.name = @XESessionName
)
BEGIN
EXEC('DROP EVENT SESSION [' + @XESessionName + '] ON SERVER;');
END
END
GO
IF EXISTS (
SELECT *
FROM sys.types
WHERE name = 'ErrorReported'
AND schema_id = SCHEMA_ID('dba')
)
DROP TYPE dba.ErrorReported;
GO
CREATE TYPE dba.ErrorReported AS TABLE (
SessionId SMALLINT,
EventName NVARCHAR(MAX),
EventTime DATETIME,
ErrorNumber INT,
Severity INT,
[State] NVARCHAR(MAX),
UserDefined NVARCHAR(MAX),
Category NVARCHAR(MAX),
Destination NVARCHAR(MAX),
IsIntercepted NVARCHAR(MAX),
[Message] NVARCHAR(MAX),
SqlText NVARCHAR(MAX)
);
GO
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba'
AND r.ROUTINE_NAME = 'CreateXESession_ErrorReported'
)
BEGIN
EXEC('CREATE PROC dba.CreateXESession_ErrorReported AS PRINT CURRENT_TIMESTAMP;');
END;
GO
ALTER PROC dba.CreateXESession_ErrorReported
/*
Purpose:
Creates and starts an Extended Events Session to monitor errors (if any) that occur.
The session is filtered by the current SPID.
Inputs: none.
History:
09/05/2016 DBA Created
*/
AS
BEGIN
DECLARE @XESessionName SYSNAME =
'Error Handling Session(SPID ' + CAST(@@SPID AS VARCHAR) + ')';
----<temp>
--INSERT INTO DbaData.dba.Debug([Message])
--VALUES('dba.CreateXESession_ErrorReported @@SPID = ' + CAST(@@SPID AS VARCHAR));
----</temp>
IF EXISTS(
SELECT *
FROM master.sys.server_event_sessions s
WHERE s.name = @XESessionName
)
BEGIN
--DECLARE @ErrMsg NVARCHAR(MAX) = 'Session ' + @XESessionName + ' already exists.';
--RAISERROR(@ErrMsg, 16, 1);
--RETURN;
/*
An XEvent session for this SPID already exists,
and apparently was never dropped.
Gather some info and email to DBA.
*/
DECLARE @Subject NVARCHAR(255) = @@SERVERNAME + ' -- Orphaned XEvent Session';
DECLARE @MsgBody NVARCHAR(MAX) = '[dba].[CreateXESession_ErrorReported] invoked at: ' +
CONVERT(VARCHAR, CURRENT_TIMESTAMP, 113) + '<br/>';
--If the session is still running, include session
--start time in the email message body.
SELECT @MsgBody = @MsgBody + 'Orphaned session started at: ' +
CONVERT(VARCHAR, r.create_time, 113) + '<br/>' + @MsgBody
FROM master.sys.dm_xe_sessions r
WHERE r.name = @XESessionName
AND r.create_time IS NOT NULL;
SELECT @MsgBody = @MsgBody + '<br/>';
DECLARE @ErrData AS dba.ErrorReported;
INSERT INTO @ErrData
EXEC dba.GetXESessionData_ErrorReported;
IF EXISTS ( SELECT 1 FROM @ErrData)
BEGIN
--If the session has gathered any error data,
--include it in the email for analysis.
SET @MsgBody = @MsgBody +
(
SELECT
d.SessionId AS td,
d.EventName AS td,
d.EventTime AS td,
d.ErrorNumber AS td,
d.Severity AS td,
d.[State] AS td,
d.UserDefined AS td,
d.Category AS td,
d.Destination AS td,
d.IsIntercepted AS td,
REPLACE(d.[Message], CHAR(13) + CHAR(10), '<br/>') AS td,
REPLACE(d.SqlText, CHAR(13) + CHAR(10), '<br/>') AS td
FROM @ErrData d
FOR XML RAW ('tr'), ROOT('table'), ELEMENTS
)
SET @MsgBody = REPLACE(@MsgBody, '<table>', '<table border="1">
<tr><th>SessionId</th><th>EventName</th><th>EventTime</th><th>ErrorNumber</th><th>Severity</th><th>State</th><th>UserDefined</th><th>Category</th><th>Destination</th><th>IsIntercepted</th><th>Message</th><th>SqlText</th></tr>');
END
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'DBA@Domain.com',
@profile_name = 'Default',
@subject = @Subject,
@body = @MsgBody,
@body_format = 'HTML';
--Drop the orphaned XEvent session to clear out the ring buffer target.
EXEC dba.DropXESession_ErrorReported;
END
--Include SPID within session name for isolation.
DECLARE @TSql NVARCHAR(MAX) = 'CREATE EVENT SESSION [' + @XESessionName + ']
ON SERVER
ADD EVENT sqlserver.error_reported
(
ACTION(
sqlserver.session_id,
sqlserver.sql_text
)
WHERE [package0].[not_equal_unicode_string]([message],N'''''''''''')
AND [severity]>(10)
AND [sqlserver].[session_id]=(' + CAST(@@SPID AS VARCHAR) + ')
)
ADD TARGET package0.ring_buffer
WITH (';
DECLARE @MajorVersion INT = CAST(SERVERPROPERTY('ProductMajorVersion') AS INT);
DECLARE @EventRetentionMode NVARCHAR(MAX) = 'NO_EVENT_LOSS'; --Default
--NO_EVENT_LOSS fails on SQL 2014 SP2 AND SQL2016 SP1
IF @MajorVersion = 12 OR @MajorVersion = 13
SET @EventRetentionMode = 'ALLOW_SINGLE_EVENT_LOSS';
SET @TSql = @TSql + '
EVENT_RETENTION_MODE=' + @EventRetentionMode + ',
MAX_MEMORY=4096 KB,
MAX_DISPATCH_LATENCY=1 SECONDS,
MAX_EVENT_SIZE=0 KB,
MEMORY_PARTITION_MODE=NONE,
TRACK_CAUSALITY=ON,
STARTUP_STATE=OFF
);'
--PRINT @TSql;
EXEC(@TSql);
SET @TSql = 'ALTER EVENT SESSION [' + @XESessionName + '] ON SERVER STATE=START;';
EXEC(@TSql);
END
GO
--This PROC is deprecated. Drop if exists.
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dbo' AND r.ROUTINE_NAME = 'GetLastErrorMessage'
)
DROP PROCEDURE dbo.GetLastErrorMessage
GO
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba' AND r.ROUTINE_NAME = 'BackupDatabases'
)
DROP PROCEDURE dba.BackupDatabases
GO
CREATE PROCEDURE dba.BackupDatabases
@DifferentialOnly BIT,
@Path VARCHAR(255),
@MirrorToPath VARCHAR(255) = NULL,
@RAISERROR BIT = 1,
@WithEncryption BIT = 0,
@ServerCertificate SYSNAME = NULL
AS
/*
Purpose:
Performs multiple database backups.
Non-system db's
Some system db's (see below)
Online db's
Db's that are not snapshots.
Inputs:
@DifferentialOnly - specify 1 for a differential backup,
or 0 for a differential backup.
@Path - the path where the backup files are to be created.
@MirrorToPath - (optional) the path where a copy of the backup files are to be created.
@RAISERROR - (optional) indicates if an error should be raised if there is a backup failure.
@WithEncryption - (optional) create backup with enctyption.
@ServerCertificate - (optional) name of server certificate.
History:
08/03/2009 DBA Created
11/03/2009 DBA Validation of backups is for ONLINE db's only.
01/29/2010 DBA Add @MirrorToPath parameter to accomodate backup to multiple locations.
@Path parameter is now required.
03/22/2011 DBA Remove TRY/CATCH block. Error_Message() only captures the last error, which
states "BACKUP DATABASE is terminating abnormally." This tells us nothing!
Instead, use xp_CmdShell to run sqlcmd.exe and save stdout to a table.
04/26/2011 DBA Allow differential backups of msdb.
05/03/2011 DBA Make msdb the last db backed up. We want the backup history of all the other db's
to be in the backup of msdb for DR purposes.
09/20/2011 DBA xp_CmdShell is still not capturing backup failure messages.
New strategy: used a CLR stored proc to call sp dba.BackupDatabase.
Added optional param @RAISERROR.
11/15/2011 DBA msdb sometimes isn't in the cursor select list. (?)
Specify cursor as CURSOR FORWARD_ONLY READ_ONLY STATIC.
02/17/2012 DBA Include [distribution] in the backups.
07/26/2013 DBA MS recommendation is to backup databases ReportServer (with FULL recovery model)
and ReportServerTempDB (with SIMPLE recovery model).
Therefore, do not exclude them.
http://msdn.microsoft.com/en-us/library/ms155814(v=sql.105).aspx
02/02/2014 DBA Include distribution in backups.
Use dba.SendMailByOperator in lieu of msdb.dbo.sp_send_dbmail
04/17/2014 DBA Yet another new strategy: use [dba].[GetLastErrorMessage] (which is
pure tsql) in lieu of CLR stored proc.
Resume use of [msdb].[dbo].[sp_send_dbmail].
09/21/2016 DBA [dba].[GetLastErrorMessage] does not get *all* the error messages.
Enhance TRY...CATCH error handling with Extended Events.
http://itsalljustelectrons.blogspot.com/2016/09/Enhanced-TSQL-Error-Handling-With-Extended-Events-Part2.html
11/04/2016 DBA Add encryption options.
11/29/2016 DBA Change @RAISERROR default to 1.
07/29/2017 DBA Exclude DBs in standby mode.
*/
DECLARE @ExcludedDB TABLE (DbName SYSNAME);
DECLARE @BackupType CHAR(1) = 'D'; --Default value: indicates a FULL backup
--This will be the body of an HTML-formatted email message.
DECLARE @Body NVARCHAR(MAX) = '<table border="1">' +
'<tr>' +
'<th>Database Name</th>' +
'<th>Error Number</th>' +
'<th>Error Message</th>' +
'</tr>';
DECLARE @BackupFailures BIT = 0;
DECLARE @ErrData AS dba.ErrorReported;
DECLARE @DbName SYSNAME;
IF @DifferentialOnly = 1
BEGIN
--No differential backups for master. (Full only.)
INSERT INTO @ExcludedDB (DbName) VALUES ('master')
SET @BackupType = 'I'
END
--These db's are never backed up.
INSERT INTO @ExcludedDB (DbName) VALUES ('tempdb')
INSERT INTO @ExcludedDB (DbName) VALUES ('model')
DECLARE curDBs CURSOR FORWARD_ONLY READ_ONLY STATIC FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE'
AND source_database_id IS NULL
AND name NOT IN
(SELECT DbName FROM @ExcludedDB)
AND is_in_standby = 0
ORDER BY CASE WHEN name = 'msdb' THEN 1 ELSE 0 END, name
OPEN curDBs;
FETCH NEXT FROM curDBs INTO @DbName;
EXEC dba.CreateXESession_ErrorReported;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
IF @BackupType = 'D'
BEGIN
EXECUTE dba.BackupDatabase_FULL
@DBName = @DbName,
@Path = @Path,
@MirrorToPath = @MirrorToPath,
@WithEncryption = @WithEncryption,
@ServerCertificate = @ServerCertificate
END
ELSE IF @BackupType = 'I'
BEGIN
EXECUTE dba.BackupDatabase_DIFF
@DBName = @DbName,
@Path = @Path,
@MirrorToPath = @MirrorToPath,
@WithEncryption = @WithEncryption,
@ServerCertificate = @ServerCertificate
END
END TRY
BEGIN CATCH
SET @BackupFailures = 1;
INSERT INTO @ErrData
EXEC dba.GetXESessionData_ErrorReported;
--Add "rows" to the HTML <table>.
SELECT @Body = @Body + CHAR(13) + CHAR(10) + '<tr>' +
'<td>' + @DbName + '</td>' +
'<td>' + CAST(e.ErrorNumber AS VARCHAR) + '</td>' +
'<td>' + e.[Message] + '</td>' +
'</tr>'
FROM @ErrData e
--Drop & recreate the XEvent session to clear out the ring buffer target.
EXEC dba.DropXESession_ErrorReported;
EXEC dba.CreateXESession_ErrorReported;
DELETE FROM @ErrData;
END CATCH
FETCH NEXT FROM curDBs INTO @DbName
END
CLOSE curDBs
DEALLOCATE curDBs
EXEC dba.DropXESession_ErrorReported;
IF @BackupFailures = 1
BEGIN
DECLARE @Subject NVARCHAR(255) = @@SERVERNAME + ' -- Backup Errors'
SET @Body = @Body + '</table>'
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'DBA@Domain.com',
@profile_name = 'Default',
@subject = @Subject,
@body = @Body,
@body_format = 'HTML'
IF @RAISERROR = 1
BEGIN
--This will cause any sql job that invokes the sp to fail.
RAISERROR('One or more backup errors occurred.', 16, 1);
RETURN
END
END
GO
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba' AND r.ROUTINE_NAME = 'BackupTransactionLogs'
)
DROP PROCEDURE dba.BackupTransactionLogs
GO
CREATE PROCEDURE dba.BackupTransactionLogs
@Path VARCHAR(255),
@MirrorToPath VARCHAR(255) = NULL,
@RAISERROR BIT = 1,
@WithEncryption BIT = 0,
@ServerCertificate SYSNAME = NULL
AS
/******************************************************************************
* Name : dba.BackupTransactionLogs
* Purpose : Performs transaction log backups on multiple databases:
* Non-system db's
* Online db's
* Db's not in standby
* Db's set to full recovery model.
* Inputs : @Path - the path where the transaction log backup files are to be created.
* @MirrorToPath - (optional) the path where a copy of the trx log backup file is to be created.
* @RAISERROR - (optional) flag to raise an error if backup failures are encountered.
* @WithEncryption - (optional) create backup with enctyption.
* @ServerCertificate - (optional) name of server certificate.
* Outputs : None
* Returns : Nothing
******************************************************************************
* Change History
* 08/03/2009 DBA Created
* 01/28/2010 DBA Add @MirrorToPath parameter to accomodate multiple backup sets.
* 02/24/2010 DBA @Path parameter is no longer optional.
* 07/26/13 DBA Don't exclude ReportServer and ReportServerTempDB.
* http://msdn.microsoft.com/en-us/library/ms155814(v=sql.105).aspx
* 02/02/2014 DBA Use dba.SendMailByOperator in lieu of msdb.dbo.sp_send_dbmail
* 04/21/2014 DBA Enhance sp for use with [dba].[GetLastErrorMessage]
* 09/21/2016 DBA [dba].[GetLastErrorMessage] does not get *all* the error messages.
* Enhance TRY...CATCH error handling with Extended Events.
* http://itsalljustelectrons.blogspot.com/2016/09/Enhanced-TSQL-Error-Handling-With-Extended-Events-Part2.html
* 11/04/2016 DBA Add encryption options.
* 11/29/2016 DBA Change @RAISERROR default to 1.
******************************************************************************/;
DECLARE @DbName SYSNAME;
DECLARE @BackupFailures BIT = 0;
DECLARE @ErrData AS dba.ErrorReported;
--This will be the body of an HTML-formatted email message.
DECLARE @Body NVARCHAR(MAX) = '<table border="1">' +
'<tr>' +
'<th>Database Name</th>' +
'<th>Error Number</th>' +
'<th>Error Message</th>' +
'</tr>';
DECLARE curDBs CURSOR FORWARD_ONLY READ_ONLY STATIC FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE'
AND is_in_standby = 0
AND recovery_model_desc = 'FULL'
AND is_read_only = 0
AND name NOT IN
(
'master', 'tempdb', 'model', 'msdb'
)
ORDER BY name
IF RIGHT(@Path, 1) != '\'
SET @Path = @Path + '\'
OPEN curDBs;
FETCH NEXT FROM curDBs INTO @DbName;
EXEC dba.CreateXESession_ErrorReported;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC dba.BackupTransactionLog
@DBName = @DbName,
@Path = @Path,
@MirrorToPath = @MirrorToPath,
@WithEncryption = @WithEncryption,
@ServerCertificate = @ServerCertificate;
END TRY
BEGIN CATCH
SET @BackupFailures = 1;
INSERT INTO @ErrData
EXEC dba.GetXESessionData_ErrorReported;
--Add "rows" to the HTML <table>.
SELECT @Body = @Body + CHAR(13) + CHAR(10) + '<tr>' +
'<td>' + @DbName + '</td>' +
'<td>' + CAST(e.ErrorNumber AS VARCHAR) + '</td>' +
'<td>' + e.[Message] + '</td>' +
'</tr>'
FROM @ErrData e
--Drop & recreate the XEvent session to clear out the ring buffer target.
EXEC dba.DropXESession_ErrorReported;
EXEC dba.CreateXESession_ErrorReported;
DELETE FROM @ErrData;
END CATCH
FETCH NEXT FROM curDBs INTO @DbName
END
CLOSE curDBs
DEALLOCATE curDBs
EXEC dba.DropXESession_ErrorReported;
IF @BackupFailures = 1
BEGIN
DECLARE @Subject NVARCHAR(255)
SET @Subject = @@SERVERNAME + ' -- Trx Log Backup Errors'
SET @Body = @Body + '</table>'
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'DBA@Domain.com',
@profile_name = 'Default',
@subject = @Subject,
@body = @Body,
@body_format = 'HTML'
IF @RAISERROR = 1
BEGIN
--This will cause any sql job that invokes the sp to fail.
RAISERROR('One or more transaction log backup errors occurred.', 16, 1);
RETURN
END
END
GO
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba' AND r.ROUTINE_NAME = 'BackupDatabasesForArchive'
)
DROP PROCEDURE dba.BackupDatabasesForArchive
GO
CREATE PROCEDURE dba.BackupDatabasesForArchive
@Path VARCHAR(255),
@MirrorToPath VARCHAR(255) = NULL,
@RAISERROR BIT = 0,
@WithEncryption BIT = 0,
@ServerCertificate SYSNAME = NULL
AS
/*
Purpose:
Performs multiple database backups for archive purposes:
[master] and [msdb] system databases
User databases that are online and are not snapshots.
Inputs:
@Path - the path where the backup files are to be created.
@MirrorToPath - (optional) the path where a copy of the backup files are to be created.
@RAISERROR - (optional) indicates if an error should be raised if there is a backup failure.
@WithEncryption - (optional) create backup with enctyption.
@ServerCertificate - (optional) name of server certificate.
History:
07/25/2016 DBA Created
09/21/2016 DBA [dba].[GetLastErrorMessage] does not get *all* the error messages.
Enhance TRY...CATCH error handling with Extended Events.
http://itsalljustelectrons.blogspot.com/2016/09/Enhanced-TSQL-Error-Handling-With-Extended-Events-Part2.html
11/04/2016 DBA Add encryption options.
07/29/2017 DBA Exclude DBs in standby mode.
*/
;
--This will be the body of an HTML-formatted email message.
DECLARE @Body NVARCHAR(MAX) = '<table border="1">' +
'<tr>' +
'<th>Database Name</th>' +
'<th>Error Number</th>' +
'<th>Error Message</th>' +
'</tr>';
DECLARE @BackupFailures BIT = 0;
DECLARE @ErrData AS dba.ErrorReported;
DECLARE @DbName SYSNAME;
DECLARE curDBs CURSOR FORWARD_ONLY READ_ONLY STATIC FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE'
AND source_database_id IS NULL
AND name NOT IN
('tempdb', 'model')
AND is_in_standby = 0
ORDER BY CASE WHEN name = 'msdb' THEN 1 ELSE 0 END, name
OPEN curDBs
FETCH NEXT FROM curDBs INTO @DbName
EXEC dba.CreateXESession_ErrorReported;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC DbaData.dba.BackupDatabase_Archive
@DBName = @DbName,
@Path = @Path,
@MirrorToPath = @MirrorToPath,
@WithEncryption = @WithEncryption,
@ServerCertificate = @ServerCertificate;
END TRY
BEGIN CATCH
SET @BackupFailures = 1;
INSERT INTO @ErrData
EXEC dba.GetXESessionData_ErrorReported;
--Add "rows" to the HTML <table>.
SELECT @Body = @Body + CHAR(13) + CHAR(10) + '<tr>' +
'<td>' + @DbName + '</td>' +
'<td>' + CAST(e.ErrorNumber AS VARCHAR) + '</td>' +
'<td>' + e.[Message] + '</td>' +
'</tr>'
FROM @ErrData e
--Drop & recreate the XEvent session to clear out the ring buffer target.
EXEC dba.DropXESession_ErrorReported;
EXEC dba.CreateXESession_ErrorReported;
DELETE FROM @ErrData;
END CATCH
FETCH NEXT FROM curDBs INTO @DbName
END
CLOSE curDBs;
DEALLOCATE curDBs;
EXEC dba.DropXESession_ErrorReported;
IF @BackupFailures = 1
BEGIN
DECLARE @Subject NVARCHAR(255)
SET @Subject = @@SERVERNAME + ' -- Backup Errors (Archives)'
SET @Body = @Body + '</table>'
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'DBA@Domain.com',
@profile_name = 'Default',
@subject = @Subject,
@body = @Body,
@body_format = 'HTML'
IF @RAISERROR = 1
BEGIN
--This will cause any sql job that invokes the sp to fail.
RAISERROR('One or more backup errors occurred.', 16, 1);
RETURN
END
END
GO
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba' AND r.ROUTINE_NAME = 'DefragmentIndexesByDatabase'
)
DROP PROCEDURE dba.DefragmentIndexesByDatabase
GO
CREATE PROCEDURE dba.DefragmentIndexesByDatabase
@DBName SYSNAME,
@MinFragmentation FLOAT = 5.0,
@ReorgVsRebuildPercentThreshold FLOAT = 30.0,
@DisplayOnly BIT = 0,
@PrintTsql BIT = 0
AS
/*
Purpose:
Defragments indexes for a specific database that are at
a certain percent fragmentation or above.
Note: avg_fragmentation_in_percent may not change after a
rebuild for some indexes, especially if there are few rows
in the table. If the page count for the table is below 100,
there's nothing to be concerned about.
History:
04/24/2014 DBA Created
06/16/2014 DBA Validate existence of index before attempting to
rebuild or reorganize.
09/18/2014 DBA If ONLINE rebuild fails, catch error and try again
with ONLINE = OFF
08/07/2015 DBA Change recovery model from FULL to BULK_LOGGED (as
needed) before defragging. Revert afterwards.
08/26/2015 DBA When a defrag attempt fails:
Try a 2nd defrag, but only if certain criteria are met.
Generate a logged error message with debugging details.
*/
DECLARE @Schema SYSNAME
DECLARE @Table SYSNAME
DECLARE @Index SYSNAME
DECLARE @AvgFragPct FLOAT
DECLARE @Tsql NVARCHAR(MAX)
DECLARE @Online NVARCHAR(8)
IF NOT EXISTS ( SELECT 1 FROM master.sys.databases WHERE name = @DBName )
BEGIN
PRINT 'Database "' + COALESCE(@DBName, '') + '" does not exist.'
RETURN
END
SELECT @Online = CASE WHEN CAST(SERVERPROPERTY ('edition') AS VARCHAR) LIKE '%Enterprise%' THEN 'ON' ELSE 'OFF' END
SELECT
CAST('' AS SYSNAME) SchemaName,
object_id TableId,
CAST('' AS SYSNAME) TableName,
index_id IndexId,
CAST('' AS SYSNAME) IndexName,
avg_fragmentation_in_percent [Avg Fragmention %],
page_count PageCount,
CAST(0 AS BIT) AS IsReadOnly
INTO #FraggedIndexes
FROM sys.dm_db_index_physical_stats(
DB_ID(@DBName), --DBName
NULL, --TableName
NULL, NULL, NULL)
WHERE index_id != 0
AND avg_fragmentation_in_percent >= @MinFragmentation
--Table_Schema + Table_Name (base tables)
SET @Tsql =
'UPDATE #FraggedIndexes ' +
'SET SchemaName = s.name ,' +
'TableName = t.name ' +
'FROM [' + @DBName + '].sys.schemas s ' +
'JOIN [' + @DBName + '].sys.tables t ' +
'ON t.schema_id = s.schema_id ' +
'WHERE t.object_id = TableId '
EXEC (@Tsql)
--View_Schema + View_Name (indexed views)
SET @Tsql =
'UPDATE #FraggedIndexes ' +
'SET SchemaName = s.name , ' +
'TableName = v.name ' +
'FROM [' + @DBName + '].sys.schemas s ' +
'JOIN [' + @DBName + '].sys.views v ' +
'ON v.schema_id = s.schema_id ' +
'WHERE v.object_id = TableId ' +
'AND SchemaName = '''' ' +
'AND TableName = '''' '
EXEC (@Tsql)
SET @Tsql =
'UPDATE #FraggedIndexes ' +
'SET IndexName = i.name, ' +
'IsReadOnly = fg.is_read_only ' +
'FROM [' + @DBName + '].sys.indexes i ' +
'JOIN [' + @DBName + '].sys.filegroups fg ' +
' ON fg.data_space_id = i.data_space_id ' +
'WHERE i.object_id = TableId ' +
'AND i.index_id = IndexId '
EXEC (@Tsql)
IF @DisplayOnly = 1
BEGIN
SELECT * FROM #FraggedIndexes ORDER BY TableName
END
ELSE
BEGIN
DECLARE curFrags CURSOR FOR
SELECT IndexName, SchemaName, TableName, [Avg Fragmention %]
FROM #FraggedIndexes
WHERE IsReadOnly = 0
ORDER BY TableName
OPEN curFrags
FETCH NEXT FROM curFrags INTO @Index, @Schema, @Table, @AvgFragPct
--Get the recovery model of the db.
DECLARE @RModel NVARCHAR(60)
SELECT @RModel = d.recovery_model_desc
FROM master.sys.databases d
WHERE d.name = @DBName
--Change recovery model from FULL to BULK_LOGGED.
IF @@FETCH_STATUS = 0 AND UPPER(@RModel) = 'FULL'
BEGIN
SET @Tsql = 'ALTER DATABASE [' + @DBName + ']
SET RECOVERY BULK_LOGGED
WITH NO_WAIT'
EXEC (@Tsql)
END
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Tsql = 'IF EXISTS (
SELECT *
FROM [' + @DBName + '].sys.indexes i
WHERE i.name = ''' + @Index + '''
AND i.object_id = OBJECT_ID(''' + @DBName + '.' + @Schema + '.' + @Table + ''')
)' + CHAR(13) + CHAR(10)
IF @AvgFragPct <= @ReorgVsRebuildPercentThreshold
SET @Tsql = @Tsql + 'ALTER INDEX [' + @Index + '] ON [' + @DBName + '].[' + @Schema + '].[' + @Table + '] REORGANIZE '
ELSE
SET @Tsql = @Tsql + 'ALTER INDEX [' + @Index + '] ON [' + @DBName + '].[' + @Schema + '].[' + @Table + '] REBUILD WITH (SORT_IN_TEMPDB = ON, ONLINE = ' + @Online + ')'
BEGIN TRY
EXEC (@Tsql)
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
DECLARE @ErrDetails VARCHAR(2000);
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
SET @ErrDetails =
'Index Defragmentation Failed. Index Name: [' + @Index + '] ' +
'Indexed Object Name: [' + @DBName + '].[' + @Schema + '].[' + @Table + '] ' +
'Fragmentation Percent: ' + CAST(@AvgFragPct AS VARCHAR);
IF @AvgFragPct > @ReorgVsRebuildPercentThreshold AND @Online = 'ON'
BEGIN
BEGIN TRY
--Try to rebuild the index as before, but offline.
SET @Tsql = REPLACE(@Tsql, 'ONLINE = ON', 'ONLINE = OFF')
EXEC (@Tsql)
END TRY
BEGIN CATCH
--If offline index rebuild still fails, throw a custom error
RAISERROR (@ErrDetails, 16, 1) WITH LOG;
--"Throw" the original error.
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
END
ELSE
BEGIN
--Throw a custom error.
RAISERROR (@ErrDetails, 16, 1) WITH LOG;
--"Throw" the original error.
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END
END CATCH
IF @PrintTsql = 1
PRINT @Tsql
FETCH NEXT FROM curFrags INTO @Index, @Schema, @Table, @AvgFragPct
END
CLOSE curFrags
DEALLOCATE curFrags
INSERT INTO dba.IndexRebuildHistory
(DatabaseName, SchemaName, TableName, IndexName, FragmentationPct, PageCount)
SELECT
@DBName,
SchemaName,
TableName,
IndexName,
[Avg Fragmention %],
PageCount
FROM #FraggedIndexes
WHERE PageCount >= 100
--If the recovery model was changed, revert to FULL.
IF EXISTS (
SELECT *
FROM master.sys.databases d
WHERE d.name = @DBName
AND d.recovery_model_desc <> 'FULL'
AND UPPER(@RModel) = 'FULL'
)
BEGIN
SET @Tsql = 'ALTER DATABASE [' + @DBName + ']
SET RECOVERY FULL
WITH NO_WAIT'
EXEC (@Tsql)
--TODO: backup t-log?
END
END
DROP TABLE #FraggedIndexes
GO
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES r
WHERE r.ROUTINE_SCHEMA = 'dba' AND r.ROUTINE_NAME = 'DefragmentIndexes'
)
DROP PROCEDURE dba.DefragmentIndexes
GO
CREATE PROCEDURE dba.DefragmentIndexes
@MinFragmentation FLOAT = 5.0,
@ReorgVsRebuildPercentThreshold FLOAT = 30.0
AS
/*
Purpose:
Defragments indexes on [master], [msdb], and user db's that are:
Online
In MULTI_USER mode
Not in standby
Not read-only
History: