/
5297_Chapter_9.sql
756 lines (594 loc) · 18.8 KB
/
5297_Chapter_9.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
----------------------------------------------------------------
--Query Optimization Basics
----------------------------------------------------------------
USE AdventureWorks
go
SELECT productModel.name as productModel,
product.name as productName
FROM production.product as product
join production.productModel as productModel
on productModel.productModelId = product.productModelId
WHERE product.name like '%glove%'
GO
----------------------------------------------------------------
-- Transaction Syntax
----------------------------------------------------------------
BEGIN TRANSACTION one
ROLLBACK TRANSACTION one
GO
----------------------------------------------------------------
BEGIN TRANSACTION one
BEGIN TRANSACTION two
ROLLBACK TRANSACTION two
GO
----------------------------------------------------------------
--Not in book
ROLLBACK TRANSACTION
GO
----------------------------------------------------------------
select recovery_model_desc
from sys.databases
where name = 'AdventureWorks'
GO
----------------------------------------------------------------
USE Master
GO
ALTER DATABASE AdventureWorks
SET RECOVERY FULL
GO
----------------------------------------------------------------
EXEC sp_addumpdevice 'disk', 'TestAdventureWorks', 'C:\Temp\AdventureWorks.bak'
EXEC sp_addumpdevice 'disk',
'TestAdventureWorksLog', 'C:\Temp\AdventureWorksLog.bak'
GO
----------------------------------------------------------------
BACKUP DATABASE AdventureWorks TO TestAdventureWorks
GO
----------------------------------------------------------------
USE AdventureWorks
GO
SELECT count(*)
FROM SALES.StoreContact
BEGIN TRANSACTION Test WITH MARK 'Test'
DELETE Sales.StoreContact
COMMIT TRANSACTION
GO
----------------------------------------------------------------
BACKUP LOG AdventureWorks to TestAdventureWorksLog
GO
----------------------------------------------------------------
USE Master
GO
RESTORE DATABASE AdventureWorks FROM TestAdventureWorks WITH REPLACE, NORECOVERY
RESTORE LOG AdventureWorks FROM TestAdventureWorksLog WITH STOPBEFOREMARK = 'Test'
GO
----------------------------------------------------------------
-- Nesting transaction
----------------------------------------------------------------
SELECT @@TRANCOUNT AS zeroDeep
BEGIN TRANSACTION
SELECT @@TRANCOUNT AS oneDeep
GO
----------------------------------------------------------------
BEGIN TRANSACTION
SELECT @@TRANCOUNT AS twoDeep
COMMIT TRANSACTION --commits very last transaction started with BEGIN TRANSACTION
SELECT @@TRANCOUNT AS oneDeep
GO
----------------------------------------------------------------
COMMIT TRANSACTION
SELECT @@TRANCOUNT AS zeroDeep
GO
----------------------------------------------------------------
BEGIN TRANSACTION
BEGIN TRANSACTION
BEGIN TRANSACTION
BEGIN TRANSACTION
BEGIN TRANSACTION
BEGIN TRANSACTION
BEGIN TRANSACTION
select @@trancount as InTran
ROLLBACK TRANSACTION
select @@trancount as OutTran
GO
----------------------------------------------------------------
COMMIT TRANSACTION
GO
----------------------------------------------------------------
----------------------------------------------------------------
-- Savepoints
----------------------------------------------------------------
USE tempDb
GO
----------------------------------------------------------------
CREATE SCHEMA arts
CREATE TABLE arts.performer
(
performerId int identity,
name varchar(100)
)
GO
BEGIN TRANSACTION
INSERT INTO arts.performer(name) VALUES ('Elvis Costello')
SAVE TRANSACTION savePoint
INSERT INTO arts.performer(name) VALUES ('Air Supply')
ROLLBACK TRANSACTION savePoint
COMMIT TRANSACTION
SELECT *
FROM arts.performer
GO
----------------------------------------------------------------
-- Stored Procedures
----------------------------------------------------------------
CREATE PROCEDURE tranTest
AS
BEGIN
SELECT @@TRANCOUNT AS trancount
BEGIN TRANSACTION
ROLLBACK TRANSACTION
END
GO
----------------------------------------------------------------
BEGIN TRANSACTION
EXECUTE tranTest
COMMIT TRANSACTION
GO
----------------------------------------------------------------
ALTER PROCEDURE tranTest
AS
BEGIN
DECLARE @savepoint varchar(32)
--gives us a unique savepoint name, which can only be 32 characters
SET @savepoint = cast(object_name(@@procid) AS varchar(29)) +
cast(@@nestlevel AS varchar(3))
BEGIN TRANSACTION
SAVE TRANSACTION @savepoint
--do something here
ROLLBACK TRANSACTION @savepoint
COMMIT TRANSACTION
END
GO
----------------------------------------------------------------
--Not in text
BEGIN TRANSACTION
EXECUTE tranTest
COMMIT TRANSACTION
GO
----------------------------------------------------------------
ALTER PROCEDURE tranTest
AS
BEGIN
DECLARE @savepoint varchar(30)
--gives us a unique savepoint name
SET @savepoint = cast(object_name(@@procid) AS varchar(27)) +
cast(@@nestlevel AS varchar(3))
BEGIN TRY
BEGIN TRANSACTION
SAVE TRANSACTION @savepoint
--do something here
RAISERROR ('ouch',16,1)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
--if the transaction has not been rolled back elsewhere (like a trigger)
--back out gracefully
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION @savepoint
COMMIT TRANSACTION
END
DECLARE @ERRORmessage varchar(2000)
SET @ERRORmessage = ERROR_MESSAGE()
RAISERROR (@ERRORmessage,16,1)
RETURN -100
END CATCH
END
GO
----------------------------------------------------------------
CREATE SCHEMA menu
CREATE TABLE menu.foodItem
(
foodItemId int not null identity(1,1)
CONSTRAINT PKmenu_foodItem PRIMARY KEY,
name varchar(30) not null
CONSTRAINT AKmenu_foodItem_name UNIQUE,
description varchar(60) not null,
CONSTRAINT CHKmenu_foodItem_name CHECK (name <> ''),
CONSTRAINT CHKmenu_foodItem_description CHECK (description <> '')
)
GO
----------------------------------------------------------------
CREATE PROCEDURE menu.foodItem$insert
(
@name varchar(30),
@description varchar(60),
@newFoodItemId int = null output --we will send back the new id here
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @savepoint varchar(30)
--gives us a unique savepoint name
SET @savepoint = cast(object_name(@@procid) AS varchar(27)) +
cast(@@nestlevel AS varchar(3))
BEGIN TRY
BEGIN TRANSACTION
SAVE TRANSACTION @savepoint
INSERT INTO menu.foodItem(name, description)
VALUES (@name, @description)
set @newFoodItemId = scope_identity() --if you use an instead of trigger
--you will have to use name to do the
--identity "grab"
COMMIT TRANSACTION
END TRY
BEGIN CATCH
--if the transaction has not been rolled back elsewhere (like a trigger)
--back out gracefully
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION @savepoint
COMMIT TRANSACTION
END
--uncomment to use the error log procedure created back in chapter 6
--EXECUTE dbo.errorLog$insert
DECLARE @ERROR_MESSAGE varchar(8000)
SET @ERROR_MESSAGE = ERROR_MESSAGE()
RAISERROR (@ERROR_MESSAGE,16,1)
RETURN -100
END CATCH
END
GO
----------------------------------------------------------------
DECLARE @foodItemId int, @retval int
EXECUTE @retval = menu.foodItem$insert @name ='Burger',
@description = 'Mmmm Burger',
@newFoodItemId = @foodItemId output
SELECT @retval as returnValue
IF @retval >= 0
SELECT foodItemId, name, description
FROM menu.foodItem
where foodItemId = @foodItemId
GO
----------------------------------------------------------------
DECLARE @foodItemId int, @retval int
EXECUTE @retval = menu.foodItem$insert @name ='Big Burger',
@description = '',
@newFoodItemId = @foodItemId output
SELECT @retval as returnValue
IF @retval >= 0
SELECT foodItemId, name, description
FROM menu.foodItem
where foodItemId = @foodItemId
GO
----------------------------------------------------------------
----------------------------------------------------------------
-- Isolation Level
----------------------------------------------------------------
CREATE TABLE dbo.testIsolationLevel
(
testIsolationLevelId int identity(1,1)
CONSTRAINT PKtestIsolationLevel PRIMARY KEY,
value varchar(10)
)
INSERT dbo.testIsolationLevel(value)
VALUES ('Value1')
INSERT dbo.testIsolationLevel(value)
VALUES ('Value2')
GO
----------------------------------------------------------------
--READ COMMITTED
--CONNECTION A
SET TRANSACTION ISOLATION LEVEL READ COMMITTED --this is the default
BEGIN TRANSACTION
INSERT INTO dbo.testIsolationLevel(value)
VALUES('Value3')
GO
----------------------------------------------------------------
/* --do this in another connection to SQL Server
--CONNECTION B
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT *
FROM dbo.testIsolationLevel
*/
GO
----------------------------------------------------------------
--CONNECTION A
COMMIT TRANSACTION
GO
----------------------------------------------------------------
--READ COMMITTED
--CONNECTION A
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRANSACTION
SELECT * FROM dbo.testIsolationLevel
GO
----------------------------------------------------------------
/*
--CONNECTION B
DELETE FROM dbo.testIsolationLevel
WHERE testIsolationLevelId = 1
*/
GO
----------------------------------------------------------------
--CONNECTION A
SELECT *
FROM dbo.testIsolationLevel
COMMIT TRANSACTION
GO
----------------------------------------------------------------
--REPEATABLE READ
--CONNECTION A
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRANSACTION
SELECT * FROM dbo.testIsolationLevel
GO
----------------------------------------------------------------
/*
--CONNECTION B
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value4')
*/
GO
----------------------------------------------------------------
/*
--CONNECTION B
DELETE FROM dbo.testIsolationLevel
WHERE value = 'Value3'
*/
GO
----------------------------------------------------------------
--CONNECTION A
SELECT * FROM dbo.testIsolationLevel
COMMIT TRANSACTION
GO
----------------------------------------------------------------
--SNAPSHOT
ALTER DATABASE tempDb
SET ALLOW_SNAPSHOT_ISOLATION ON
GO
----------------------------------------------------------------
--CONNECTION A
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
BEGIN TRANSACTION
SELECT * from dbo.testIsolationLevel
GO
----------------------------------------------------------------
/*
--CONNECTION B
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value5')
*/
GO
----------------------------------------------------------------
/*
--CONNECTION B
DELETE FROM dbo.testIsolationLevel
WHERE value = 'Value4'
*/
GO
----------------------------------------------------------------
--CONNECTION A
UPDATE dbo.testIsolationLevel
SET value = 'Value2-mod'
WHERE testIsolationLevelId = 2
GO
----------------------------------------------------------------
--CONNECTION A
COMMIT TRANSACTION
SELECT * from dbo.testIsolationLevel
GO
----------------------------------------------------------------
--CONNECTION A
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
BEGIN TRANSACTION
--touch the data
SELECT * from dbo.testIsolationLevel
GO
----------------------------------------------------------------
/*
--CONNECTION B
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
update dbo.testIsolationLevel
set value = 'Value5-mod2'
where testIsolationLevelId = 6 --might be different in yours
*/
GO
----------------------------------------------------------------
update dbo.testIsolationLevel
set value = 'Value5-mod'
where testIsolationLevelId = 6 --might be different in yours
Msg 3960, Level 16, State 2, Line 1
Snapshot isolation transaction aborted due to update conflict. You cannot use snapshot isolation to access table 'dbo.testIsolationLevel' directly or indirectly in database 'tempdb' to update, delete, or insert the row that has been modified or deleted by another transaction. Retry the transaction or change the isolation level for the update/delete statement.
----------------------------------------------------------------
--Application locks
----------------------------------------------------------------
--Connection A
BEGIN TRANSACTION
DECLARE @result int
EXEC @result = sp_getapplock @Resource = 'invoiceId=1', @LockMode = 'Exclusive'
SELECT @result
GO
----------------------------------------------------------------
/*
--Connection B
BEGIN TRANSACTION
DECLARE @result int
EXEC @result = sp_getapplock @Resource = 'invoiceId=1', @LockMode = 'Shared'
PRINT @result
*/
GO
----------------------------------------------------------------
/*
--Connection B
BEGIN TRANSACTION
SELECT APPLOCK_TEST('public','invoiceId=1','Exclusive','Transaction') as CanTakeLock
ROLLBACK TRANSACTION
*/
GO
----------------------------------------------------------------
--Not in text
COMMIT TRANSACTION
GO
----------------------------------------------------------------
----------------------------------------------------------------
--Optimistic locks
----------------------------------------------------------------
CREATE SCHEMA hr
CREATE TABLE hr.person
(
personId int IDENTITY(1,1) CONSTRAINT PKperson primary key,
firstName varchar(60) NOT NULL,
middleName varchar(60) NOT NULL,
lastName varchar(60) NOT NULL,
dateOfBirth datetime NOT NULL,
rowLastModifyDate datetime NOT NULL
CONSTRAINT DFLTperson_rowLastModifyDate default getdate(),
rowModifiedByUserIdentifier nvarchar(128) NOT NULL
CONSTRAINT DFLTperson_rowModifiedByUserIdentifier default suser_sname()
)
--Note the two columns for our optimistic lock, named rowLastModifyDate and
GO
----------------------------------------------------------------
CREATE TRIGGER hr.person$InsteadOfUpdate
ON hr.person
INSTEAD OF UPDATE AS
BEGIN
DECLARE @rowsAffected int, --stores the number of rows affected
@msg varchar(2000) --used to hold the error message
SET @rowsAffected = @@rowcount
--no need to continue on if no rows affected
IF @rowsAffected = 0 return
SET NOCOUNT ON --to avoid the rowcount messages
SET ROWCOUNT 0 --in case the client has modified the rowcount
BEGIN TRY
--[validation blocks]
--[modification blocks]
--remember to update ALL columns when building instead of triggers
UPDATE hr.person
SET firstName = inserted.firstName,
middleName = inserted.middleName,
lastName = inserted.lastName,
dateOfBirth = inserted.dateOfBirth,
rowLastModifyDate = default, --tells SQL Server to set the value to
rowModifiedByUserIdentifier = default --the value in the default
FROM hr.person --contraint
JOIN inserted
on hr.person.personId = inserted.personId
END TRY
BEGIN CATCH
IF @@trancount > 0
ROLLBACK TRANSACTION
--EXECUTE dbo.errorLog$insert
DECLARE @ERROR_MESSAGE varchar(8000)
SET @ERROR_MESSAGE = ERROR_MESSAGE()
RAISERROR (@ERROR_MESSAGE,16,1)
END CATCH
END
GO
----------------------------------------------------------------
INSERT INTO hr.person (firstName, middleName, lastName, dateOfBirth)
VALUES ('Leroy','T','Brown','19391212')
SELECT *
FROM hr.person
GO
----------------------------------------------------------------
UPDATE hr.person
SET middleName = 'Tee'
WHERE personId = 1
SELECT rowLastModifyDate
FROM hr.person
GO
----------------------------------------------------------------
ALTER TABLE hr.person
ADD rowversion rowversion
GO
SELECT personId, rowversion
FROM hr.person
GO
----------------------------------------------------------------
----------------------------------------------------------------
--Coding for Row-Level Optimistic Locking
----------------------------------------------------------------
UPDATE hr.person
SET firstName = 'Fred'
WHERE personId = 1 --include the key
and firstName = 'Leroy'
and middleName = 'Tee'
and lastName = 'Brown'
and dateOfBirth = '19391212'
GO
----------------------------------------------------------------
UPDATE hr.person
SET firstName = 'Fred'
WHERE personId = 1 --include the key
and rowLastModifyDate = '<get the date>'
GO
----------------------------------------------------------------
UPDATE hr.person
SET firstName = 'Fred'
WHERE personId = 1
and rowversion = get the row value
GO
----------------------------------------------------------------
DELETE FROM hr.person
WHERE rowversion = get the row value
GO
----------------------------------------------------------------
----------------------------------------------------------------
--Logical Unit of Work
----------------------------------------------------------------
CREATE SCHEMA invoicing
go
--leaving off who invoice is for
CREATE TABLE invoicing.invoice
(
invoiceId int IDENTITY(1,1),
number varchar(20) NOT NULL,
objectVersion rowversion not null,
constraint PKinvoicing_invoice primary key (invoiceId)
)
--also forgetting what product that the line item is for
CREATE TABLE invoicing.invoiceLineItem
(
invoiceLineItemId int NOT NULL,
invoiceId int NULL,
itemcCount int NOT NULL,
cost int NOT NULL,
constraint PKinvoicing_invoiceLineItem primary key (invoiceLineItemId),
constraint FKinvoicing_invoiceLineItem$references$invoicing_invoice
foreign key (invoiceId) references invoicing.invoice(invoiceId)
)
GO
----------------------------------------------------------------
CREATE PROCEDURE invoiceLineItem$del
(
@invoiceId int, --we pass this because the client should have it
--with the invoiceLineItem row
@invoiceLineItemId int,
@objectVersion rowversion
) as
BEGIN
BEGIN TRY
BEGIN TRANSACTION
UPDATE invoice
SET number = number
WHERE invoiceId = @invoiceId
And objectVersion = @objectVersion
DELETE invoiceLineItem
FROM invoiceLineItem
WHERE invoiceLineItemId = @invoiceLineItemId
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@trancount > 0
ROLLBACK TRANSACTION
--or this will get rolled back
--EXECUTE dbo.errorLog$insert
DECLARE @ERROR_MESSAGE varchar(8000)
SET @ERROR_MESSAGE = ERROR_MESSAGE()
RAISERROR (@ERROR_MESSAGE,16,1)
END CATCH
END
GO
----------------------------------------------------------------