/
chapter 12.sql
847 lines (660 loc) · 20.3 KB
/
chapter 12.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
----------------------------------------------------------------------
--Triggers - Accessing Modified Rows
----------------------------------------------------------------------
--build a trigger that returns as a result set as
--inserted and deleted tables for demonstration purposes
--only. For real triggers, this is a bad idea
CREATE TRIGGER artist$afterUpdate$showInsertedAndDeleted
ON artist
AFTER UPDATE -- fires after the update has occurred
AS
SELECT 'contents of inserted' -- informational output
SELECT *
FROM INSERTED
SELECT 'contents of deleted' -- informational output
SELECT *
FROM DELETED
GO
UPDATE artist
SET name = UPPER(name)
go
----------------------------------------------------------------------
-- Triggers - Determining which Columns have been Modified
----------------------------------------------------------------------
CREATE TABLE columnUpdatedTest
(
columnUpdatedTestId int IDENTITY, --bitmask value 1
column1 int, --bitmask value 2
column2 int, --bitmask value 4
column3 int --bitmask value 8
)
go
CREATE TRIGGER testIt
ON columnUpdatedTest
AFTER INSERT,UPDATE
AS
IF update(columnUpdatedTestId)
BEGIN
SELECT 'columnUpdatedTestId modified'
END
IF update(column1)
BEGIN
SELECT 'column1 modified'
END
IF update(column2)
BEGIN
SELECT 'column2 modified'
END
IF update(column3)
BEGIN
SELECT 'column3 modified'
END
GO
----------------------------
INSERT columnUpdatedTest(column1,column2, column3)
VALUES (1,1,1)
go
----------------------------
UPDATE columnUpdatedTest
SET column2 = 2
WHERE columnUpdatedTestId = 1
go
----------------------------------------------------------------------
--Triggers - Writing Multi-row Validations
----------------------------------------------------------------------
CREATE TRIGGER artist$afterUpdate$demoMultiRow
ON artist
AFTER INSERT, UPDATE --fires after the insert and update has occurred
AS
IF NOT EXISTS ( SELECT *
FROM INSERTED
WHERE name IN ('the who','the beatles','jethro tull')
)
BEGIN
SELECT 'Invalid artist validation 1'
END
IF EXISTS ( SELECT *
FROM INSERTED
WHERE name NOT IN ('the who','the beatles','jethro tull')
)
BEGIN
SELECT 'Invalid artist validation 2'
END
GO
----------------------------
BEGIN TRANSACTION
INSERT INTO artist (name, defaultFl, catalogNumberMask)
VALUES ('ROLLING STONES',0,'%')
ROLLBACK TRANSACTION --undo our test rows
go
----------------------------
BEGIN TRANSACTION
INSERT INTO artist (name, defaultFl, catalogNumberMask)
SELECT 'ROLLING STONES',0,'%'
UNION
SELECT 'JETHRO TULL',0,'%'
ROLLBACK TRANSACTION --undo our test rows
go
----------------------------------------------------------------------
--Having multiple triggers for the same action
----------------------------------------------------------------------
CREATE TABLE tableA
(
field varchar(40) NOT NULL
)
CREATE TABLE tableB
(
field varchar(40) not NULL
)
GO
----------------------------
CREATE TRIGGER tableA$afterUpdate$demoNestRecurse
ON tableA
AFTER INSERT
AS
--tell the user that the trigger has fired
SELECT 'table a insert trigger'
--insert the values into tableB
INSERT INTO tableB (field)
SELECT field
FROM INSERTED
GO
CREATE TRIGGER tableB$afterUpdate$demoNestRecurse
ON tableB
AFTER INSERT
AS
--tell the user that the trigger has fired
SELECT 'table b insert trigger'
--insert the values into tableB
INSERT INTO tableA (field)
SELECT field
FROM INSERTED
GO
EXEC sp_configure 'nested triggers', 0 -- (1 = on, 0 = off)
RECONFIGURE --required for immediate acting server configuration
go
----------------------------
INSERT INTO tableA (field)
VALUES ('test value')
go
EXEC sp_configure 'nested triggers', 1 -- where 1 = ON, 0 = OFF
RECONFIGURE
EXEC sp_dboption 'bookTest','recursive triggers','FALSE'
go
----------------------------
INSERT INTO tableA (field)
VALUES ('test value')
go
----------------------------
--not in book. Forgot the recursive trigger
EXEC sp_configure 'nested triggers', 1 -- where 1 = ON, 0 = OFF
RECONFIGURE
EXEC sp_dboption 'bookTest','recursive triggers','TRUE'
go
ALTER TRIGGER tableA$afterUpdate$demoNestRecurse
ON tableA
AFTER INSERT
AS
--tell the user that the trigger has fired
SELECT 'table a insert trigger'
--insert the values into tableB
INSERT INTO tableA (field)
SELECT field
FROM INSERTED
GO
----------------------------
INSERT INTO tableA (field)
VALUES ('test value')
go
----------------------------------------------------------------------
--After triggers
----------------------------------------------------------------------
CREATE TRIGGER artist$trInsertDemo ON artist
AFTER INSERT
AS
SELECT 'contents of inserted'
SELECT artistId, name --just PK and name so it fits on a line in the book
FROM INSERTED
SELECT 'contents of artist'
SELECT artistId, name
FROM artist
GO
INSERT INTO artist (name)
VALUES ('jethro tull')
go
----------------------------------------------------------------------
--Implementing Multiple AFTER Triggers
----------------------------------------------------------------------
--not in book. turn the recursive triggers back off
EXEC sp_configure 'nested triggers', 0 -- where 1 = ON, 0 = OFF
RECONFIGURE
EXEC sp_dboption 'bookTest','recursive triggers','FALSE'
go
ALTER TRIGGER tableA$afterUpdate$demoNestRecurse
ON tableA
AFTER INSERT
AS
SELECT 'table a insert trigger'
INSERT INTO tableB (field)
VALUES (object_name(@@procid)) --@@procid gives the object_id of the
--of the current executing procedure
GO
CREATE TRIGGER tableA$afterUpdate$demoNestRecurse2
ON tableA
AFTER INSERT
AS
SELECT 'table a insert trigger2'
INSERT INTO tableB (field)
VALUES (object_name(@@procid))
GO
CREATE TRIGGER tableA$afterUpdate$demoNestRecurse3
ON tableA
AFTER INSERT
AS
SELECT 'table a insert trigger3'
INSERT INTO tableB (field)
VALUES (object_name(@@procid))
GO
----------------------------
--truncate table deletes the rows in the table very fast with a single log
--entry, plus it resets the identity values
TRUNCATE TABLE tableA
TRUNCATE TABLE tableB
go
INSERT INTO tableA
VALUES ('Test Value')
go
SELECT * FROM tableA
SELECT * FROM tableB
go
----------------------------
EXEC sp_settriggerorder
@triggerName = 'tableA$afterUpdate$demoNestRecurse3',
@order = 'first',
@stmttype = 'insert'
GO
TRUNCATE TABLE tableA
TRUNCATE TABLE tableB
INSERT INTO tableA
VALUES ('Test Value')
SELECT * FROM tableA
SELECT * FROM tableB
GO
--------------------------------------------------------------------------------
--Using AFTER Triggers to Solve Common Problems
--------------------------------------------------------------------------------
/*
CREATE TRIGGER <triggerName>
ON <tableName>
FOR <action> AS
------------------------------------------------------------------------------
-- Purpose : Trigger on the <action> that fires for any <action> DML
------------------------------------------------------------------------------
BEGIN
DECLARE @rowsAffected int, --stores the number of rows affected
@errNumber int, --used to hold the error number after DML
@msg varchar(255), --used to hold the error message
@errSeverity varchar(20),
@triggerName sysname
SET @rowsAffected = @@rowcount
SET @triggerName = object_name(@@procid) --used for messages
--no need to continue on if no rows affected
IF @rowsAffected = 0 return
<insert snippets here >
END
*/
--------------------------------------------------------------------------------
--Cascading Inserts
--------------------------------------------------------------------------------
create table url
(
urlId int identity,
url varchar(400) not null
)
create table urlStatusType
(
urlStatusTypeId int identity,
name varchar(60) not null,
defaultFl bit not null
)
create table urlStatus
(
urlStatusId int identity,
urlStatusTypeId int not null,
urlId int not null
)
go
CREATE TRIGGER url$afterInsert$autoSetStatus
ON url
FOR insert AS
------------------------------------------------------------------------------
-- Purpose : Trigger on the <action> that fires for any <action> DML
------------------------------------------------------------------------------
BEGIN
DECLARE @rowsAffected int, --stores the number of rows affected
@errorNumber int, --used to hold the error number after DML
@msg varchar(255), --used to hold the error message
@errSeverity varchar(20),
@triggerName sysname
SET @rowsAffected = @@rowcount
SET @triggerName = object_name(@@procid) --used for messages
--no need to continue on if no rows affected
IF @rowsAffected = 0 return
--add a record to the urlStatus table to tell it that the new record
--should start out as the default status
INSERT INTO urlType (urlId, urlTypeId)
SELECT INSERTED.urlId, urlType.urlTypeId
FROM INSERTED
CROSS JOIN urlType --use cross join with a where clause
--as this is not technically a join between
--INSERTED and urlType
WHERE urlType.defaultFl = 1
SET @errorNumber = @@error
IF @errorNumber <> 0
BEGIN
SET @msg = 'Error: ' + CAST(@errorNumber as varchar(10)) +
' occurred during the creation of urlStatus'
RAISERROR 50000 @msg
ROLLBACK TRANSACTION
RETURN
END
END
--------------------------------------------------------------------------------
--range checks
--------------------------------------------------------------------------------
CREATE TRIGGER urlStatusType$afterUpdate$rangeCheck
ON urlStatusType
FOR update AS
------------------------------------------------------------------------------
-- Purpose : Trigger on the <action> that fires for any <action> DML
------------------------------------------------------------------------------
BEGIN
DECLARE @rowsAffected int, --stores the number of rows affected
@errorNumber int, --used to hold the error number after DML
@msg varchar(255), --used to hold the error message
@errSeverity varchar(20),
@triggerName sysname
SET @rowsAffected = @@rowcount
SET @triggerName = object_name(@@procid) --used for messages
--no need to continue on if no rows affected
IF @rowsAffected = 0 return
--if the defaultFl column was modified
IF UPDATE(defaultFl)
BEGIN
--update any other rows in the status type table to not default if
--a row was inserted that was set to default
UPDATE urlStatusType
SET defaultFl = 0
FROM urlStatusType
--only rows that were already default
WHERE urlStatusType.defaultFl = 1
--and not in the inserted rows
AND urlStatusTypeid NOT IN
( SELECT urlStatusTypeId
FROM inserted
WHERE defaultFl = 1
)
SET @errorNumber = @@error
IF @errorNumber <> 0
BEGIN
SET @msg = 'Error: ' + CAST(@errorNumber as varchar(10)) +
' occurred during the modification of defaultFl'
RAISERROR 50000 @msg
ROLLBACK TRANSACTION
RETURN
END
--see if there is more than 1 row set to default
--like if the user updated more than one in a single operation
IF ( SELECT count(*)
FROM urlStatusType
WHERE urlStatusType.defaultFl = 1 ) > 1
BEGIN
SET @msg = 'Too many rows with default flag = 1'
RAISERROR 50000 @msg
ROLLBACK TRANSACTION
RETURN
END
END
END
go
--------------------------------------------------------------------------------
--Cascading Deletes Setting the values of Child Tables to NULL
--------------------------------------------------------------------------------
create table company
(
companyId int identity,
name varchar(60) not null,
urlId int null
)
go
CREATE TRIGGER company$afterDelete$cascadeSetNull
ON company
FOR delete AS
------------------------------------------------------------------------------
-- Purpose : Trigger on the <action> that fires for any <action> DML
------------------------------------------------------------------------------
BEGIN
DECLARE @rowsAffected int, --stores the number of rows affected
@errorNumber int, --used to hold the error number after DML
@msg varchar(255), --used to hold the error message
@errSeverity varchar(20),
@triggerName sysname
SET @rowsAffected = @@rowcount
SET @triggerName = object_name(@@procid) --used for messages
--no need to continue on if no rows affected
IF @rowsAffected = 0 return
UPDATE company
SET urlId = NULL
FROM DELETED
JOIN company
ON DELETED.urlId = company.urlId
SET @errorNumber = @@error
IF @errorNumber <> 0
BEGIN
SET @msg = 'Error: ' + CAST(@errorNumber as varchar(10)) +
' occurred during delete cascade set NULL'
RAISERROR 50000 @msg
ROLLBACK TRANSACTION
RETURN
END
END
go
----------------------------------------------------------------------
-- Instead of Trigger
----------------------------------------------------------------------
CREATE TRIGGER artist$insteadOfInsert ON artist
INSTEAD OF INSERT
AS
--output the contents of the inserted table
SELECT 'contents of inserted'
SELECT * FROM inserted
--output the contents of the physical table
SELECT 'contents of artist'
SELECT * FROM artist
GO
----------------------------
INSERT INTO artist (name)
VALUES ('John Tesh')
go
SELECT artistId, name
FROM artist
go
----------------------------
--not in text. Need to drop existing trigger
drop trigger artist$insteadOfInsert
drop trigger artist$insteadOfDelete
go
CREATE TRIGGER artist$insteadOfInsert on artist
INSTEAD OF INSERT
AS
-- must mimic the operation we are doing "instead of".
-- note that must supply a column list for the insert
-- and we cannot simply do a SELECT * FROM INSERTED because of the
-- identity column, which complains when you try to pass it a value
INSERT INTO artist(name, defaultFl, catalogNumberMask)
SELECT name, defaultFl, catalogNumberMask
FROM INSERTED
GO
CREATE TRIGGER artist$insteadOfDelete on artist
INSTEAD OF DELETE
AS
-- must mimic the operation we are doing "instead of"
DELETE FROM artist
FROM DELETED
-- we always join the inserted and deleted tables
-- to the real table via the primary key,
JOIN ARTIST
ON DELETED.artistId = artist.artistId
go
----------------------------
INSERT INTO artist(name, defaultFl, catalogNumberMask)
VALUES ('raffi',0,'%')
SELECT * FROM artist WHERE name = 'raffi'
go
----------------------------
DELETE FROM artist
WHERE name = 'raffi'
go
SELECT * FROM artist WHERE name = 'raffi'
go
----------------------------------------------------------------------
--Uses of Instead-Of Triggers - automatically maintaining fields
----------------------------------------------------------------------
drop trigger artist$insteadOfInsert
go
CREATE TRIGGER artist$insteadOfInsert ON artist
INSTEAD OF INSERT
AS
INSERT INTO artist(name, defaultFl, catalogNumberMask)
SELECT dbo.string$properCase(name), defaultfl, catalogNumberMask
FROM INSERTED
GO
CREATE TRIGGER artist$insteadOfUpdate on artist
INSTEAD OF UPDATE
AS
UPDATE artist
SET name = dbo.string$properCase(INSERTED.name),
defaultFl = INSERTED.defaultFl,
catalogNumberMask = INSERTED.catalogNumberMask
FROM artist
JOIN INSERTED ON artist.artistId = INSERTED.artistId
GO
----------------------------
-- insert fairly obviously improperly formatted name
INSERT INTO artist (name, defaultFl, catalogNumberMask)
VALUES ('eLvIs CoStElLo',0,'77_______')
-- then retrieve the last inserted value into this table
SELECT artistId, name
FROM artist
WHERE artistId = ident_current('artist')
go
----------------------------
SELECT artistId, name
FROM artist
go
UPDATE artist
SET name = UPPER(name)
go
SELECT artistId, name
FROM artist
go
----------------------------------------------------------------------
--Uses of Instead-Of Triggers - Conditional Insert
----------------------------------------------------------------------
ALTER TABLE album
DROP CONSTRAINT chkAlbum$catalogNumber$function$artist$catalogNumberValidate
go
----------------------------
CREATE TABLE albumException
(
albumExceptionId int NOT NULL IDENTITY,
name varchar(60) NOT NULL,
artistId int NOT NULL,
catalogNumber char(12) NOT NULL,
exceptionAction char(1),
exceptionDate datetime
)
go
----------------------------
CREATE TRIGGER album$insteadOfUpdate
ON album
INSTEAD OF UPDATE
AS
DECLARE @errorValue int -- this is the variable for capturing error status
UPDATE album
SET name = INSERTED.name, artistId = INSERTED.artistId,
catalogNumber = INSERTED.catalogNumber
FROM inserted
JOIN album
ON INSERTED.albumId = album.albumId
-- only update rows where the criteria is met
WHERE dbo.album$catalogNumbervalidate(INSERTED.catalogNumber,
INSERTED.artistId) = 1
-- check to make certain that an error did not occur in this statement
SET @errorValue = @@error
IF @errorValue <> 0
BEGIN
RAISERROR 50000 'Error inserting valid album records'
ROLLBACK TRANSACTION
RETURN
END
-- get all of the rows where the criteria is not met
INSERT INTO albumException (name, artistId, catalogNumber, exceptionAction,
exceptionDate)
SELECT name, artistId, catalogNumber, 'U',getdate()
FROM INSERTED
WHERE NOT( -- generally the easiest way to do this is to copy
-- the criteria and do a not(where ...)
dbo.album$catalogNumbervalidate(INSERTED.catalogNumber,
INSERTED.artistId) = 1 )
SET @errorValue = @@error
IF @errorValue <> 0
BEGIN
RAISERROR 50000 'Error logging exception album records'
ROLLBACK TRANSACTION
RETURN
END
GO
----------------------------
-- update the album table with a known good match to the catalog number
UPDATE album
SET catalogNumber = '222-22222-22'
WHERE name = 'the white album'
-- then list the artistId and catalogNumber of the album in the "real" table
SELECT artistId, catalogNumber
FROM album
WHERE name = 'the white album'
-- as well as the exception table
SELECT artistId, catalogNumber, exceptionAction, exceptionDate
FROM albumException
WHERE name = 'the white album'
go
----------------------------
UPDATE album
SET catalogNumber = '1'
WHERE name = 'the white album'
-- then list the artistId and catalogNumber of the album in the "real" table
SELECT artistId, catalogNumber
FROM album
WHERE name = 'the white album'
-- as well as the exception table
SELECT artistId, catalogNumber, exceptionAction, exceptionDate
FROM albumException
WHERE name = 'the white album'
go
----------------------------
-- create view, excluding the defaultFl column, which we don't want to let
-- users see in this view, and we want to view the names in upper case.
CREATE VIEW vArtistExcludeDefault
AS
SELECT artistId, UPPER(name) AS name, catalogNumberMask
FROM artist
GO
-- then we create a very simple INSTEAD OF insert trigger
CREATE TRIGGER vArtistExcludeDefault$insteadOfInsert
ON vArtistExcludeDefault
INSTEAD OF INSERT
AS
BEGIN
--note that we don't use the artistId from the INSERTED table
INSERT INTO artist (name, catalogNumberMask, defaultFl)
SELECT NAME, catalogNumberMask, 0 --only can set defaultFl to 0
--using the view
FROM INSERTED
END
GO
----------------------------
INSERT INTO vArtistExcludeDefault (name, catalogNumberMask)
VALUES ('The Monkees','44_______')
go
----------------------------
INSERT INTO vArtistExcludeDefault (artistId, name, catalogNumberMask)
VALUES (-1, 'The Monkees','44_______')
SELECT * FROM vArtistExcludeDefault
WHERE artistId = ident_current('vArtistExcludeDefault')
go
----------------------------------------------------------------------
--Optionally Cascading Deletes
----------------------------------------------------------------------
CREATE PROCEDURE account$delete
(
@accountId int,
@removeChildTransactionsFl bit = 0
) as
-- if they asked to delete them, just delete them
IF @removeChildTransactionsFl = 1
DELETE [transaction] --table named with keyword
WHERE accountId = @accountId
ELSE --check for existance
BEGIN
IF EXISTS (SELECT *
FROM [transaction]
WHERE accountId = @accountId)
BEGIN
RAISERROR 50000 'Child transactions exist'
RETURN -100
END
END
DELETE account
WHERE accountID = @accountId
go