/
Chapter 13.sql
1574 lines (1234 loc) · 43.2 KB
/
Chapter 13.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
--Note that the exact data that is returned from these queries will vary slightly from what is in
--the text of the book. The examples were not developed in the linear manner that the
--examples may be executed in this script
-----------------------------------------------------------------------------------
--Transactions
-----------------------------------------------------------------------------------
BEGIN TRANSACTION --start a transaction
-- insert two records
INSERT INTO artist (name)
VALUES ('mariah carey')
INSERT INTO artist (name)
VALUES ('britney spears')
-- make sure that they are in the database
SELECT artistId, name FROM artist
go
-----------------------------------
ROLLBACK TRANSACTION
SELECT artistId, name FROM artist
go
-----------------------------------
SELECT @@trancount AS zero
BEGIN TRANSACTION
SELECT @@trancount AS one
BEGIN TRANSACTION
SELECT @@trancount AS two
BEGIN TRANSACTION
SELECT @@trancount AS three
COMMIT TRANSACTION
SELECT @@trancount AS two
COMMIT TRANSACTION
SELECT @@trancount AS one
COMMIT TRANSACTION
SELECT @@trancount AS zero
go
-----------------------------------
SELECT @@trancount AS one
BEGIN TRANSACTION
SELECT @@trancount AS two
BEGIN TRANSACTION
SELECT @@trancount AS three
BEGIN TRANSACTION
SELECT @@trancount AS four
ROLLBACK TRANSACTION
SELECT @@trancount AS zero
go
-----------------------------------
BEGIN TRANSACTION --start a transaction
--insert two records
INSERT INTO artist (name)
VALUES ('moody blues')
SAVE TRANSACTION britney
INSERT INTO artist (name)
VALUES ('britney spears')
--make sure that they are in the database
SELECT artistId, name FROM artist
go
-----------------------------------
ROLLBACK TRANSACTION britney
COMMIT TRANSACTION
SELECT artistId, name FROM artist
GO
-----------------------------------------------------------------------------------
--Isolation Levels
-----------------------------------------------------------------------------------
CREATE TABLE testIsolationLevel
(
testIsolationLevelId INT IDENTITY,
value varchar(10)
)
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value1')
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value2')
go
-----------------------------------
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
--set for illustrative purposes only. If we do not set this on a connection
--it will be in read committed mode anyway because this is the default.
BEGIN TRANSACTION
SELECT * FROM dbo.testIsolationLevel
go
-----------------------------------
--***************************************************************
--open a different connection to execute this code
--***************************************************************
/*
DELETE FROM dbo.testIsolationLevel
WHERE testIsolationLevelId = 1
*/
-----------------------------------
SELECT * FROM dbo.testIsolationLevel
COMMIT TRANSACTION
go
-----------------------------------
--not in text. This code will reset our example
--clean out and reload the tables
truncate table testIsolationLevel
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value1')
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value2')
go
-----------------------------------
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRANSACTION
SELECT * FROM dbo.testIsolationLevel
go
--***************************************************************
--open a different connection to execute this code
--***************************************************************
/*
DELETE FROM dbo.testIsolationLevel
WHERE testIsolationLevelId = 1
*/
-----------------------------------
SELECT * FROM dbo.testIsolationLevel
COMMIT TRANSACTION
go
-----------------------------------
--not in text. This code will reset our example
--clean out and reload the tables
truncate table testIsolationLevel
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value1')
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value2')
go
-----------------------------------
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
SELECT * FROM dbo.testIsolationLevel
go
--***************************************************************
--open a different connection to execute this code
--***************************************************************
/*
INSERT INTO dbo.testIsolationLevel(value)
VALUES ('Value3')
*/
SELECT * FROM dbo.testIsolationLevel
COMMIT TRANSACTION
go
-----------------------------------------------------------------------------------
--Temporary tables
-----------------------------------------------------------------------------------
--create the table to hold the names of the objects
CREATE TABLE #counting
(
specific_name sysname
)
--insert all of the rows that have between 2 and 3 parameters
INSERT INTO #counting (specific_name)
SELECT specific_name
FROM information_schema.parameters as parameters
GROUP BY specific_name
HAVING COUNT(*) between 2 and 3
--count the number of values in the table
SELECT COUNT(*)
FROM #counting
DROP TABLE #counting
go
-----------------------------------
SELECT count(*)
FROM (SELECT specific_name
FROM information_schema.parameters AS parameters
GROUP BY specific_name
HAVING count(*) between 2 and 3 ) AS TwoParms
go
-----------------------------------
--recursive table example
--first we create the type table
CREATE TABLE type
(
typeId int, --not identity because we need to reference
--it in this test script
parentTypeId int NULL,
name varchar(60) NOT NULL,
)
--then we have to populate the type table
INSERT INTO type (typeId, parentTypeId, name)
VALUES (1, NULL, 'Top')
INSERT INTO type (typeId, parentTypeId, name)
VALUES (2,1, 'TopChild1')
INSERT INTO type (typeId, parentTypeId, name)
VALUES (3,1, 'TopChild2')
INSERT INTO type (typeId, parentTypeId, name)
VALUES (4,2, 'TopChild1Child1')
INSERT INTO type (typeId, parentTypeId, name)
VALUES (5,2, 'TopChild1Child2')
go
-----------------------------------
CREATE TABLE #holdItems
(
typeId int NOT NULL, --pkey of type table
parentTypeID int NULL, --recursive attribute
name varchar(100), --name of the type
indentLevel int, --level of the tree for indenting display
sortOrder varchar(1000) --sort order for final display
)
go
-----------------------------------
--get the toplevel items
INSERT INTO #holdItems
-- First pass will start at indentLevel 1. We put the parent primary key into
-- the sortOrder, padded with zeroes to the right, then we will append each
-- level of child to each sublevel
SELECT typeId, parentTypeID, name, 1 AS indentLevel,
LTRIM(replicate('0',10 - LEN(CAST(typeId AS char(10)))) +
CAST(typeId AS char(10))) AS sortOrder
FROM dbo.type
WHERE parentTypeID IS NULL --parent is NULL means top node
go
-----------------------------------
DECLARE @currLevel int
SET @currLevel = 2
WHILE 1=1 -- since there is no repeat until in T-SQL
BEGIN
INSERT INTO #holdItems
-- add the sort order of this item to current sort order
-- of the parent's sort order
SELECT type.TypeId, type.parentTypeID, type.name,
@currLevel AS indentLevel,
RTRIM(#holdItems.sortOrder) +
LTRIM(replicate('0',10 - LEN(CAST(type.typeId AS char(10)))) +
CAST(type.typeId as char(10)))
FROM dbo.type AS type
-- this join gets us the child records of the items in the
-- #holdItemsTable
JOIN #holdItems
ON Type.parentTypeId = #holdItems.typeId
-- currlevel tells us the level we are adding, so we need the parent
-- in the @join
WHERE #holdItems.indentLevel = @currLevel - 1
-- if there are no children on the new level, we break
IF @@rowcount = 0
BREAK
-- otherwise we simply increment the counter and move on.
SET @currLevel = @currLevel + 1
END
-----------------------------------
SELECT typeId, parentTypeId, CAST(name AS varchar(15)) AS name, indentLevel
FROM #holdItems
ORDER BY sortorder, parentTypeID
-- drop table is not explicitly required if in a stored procedure or if
-- we disconnect between executions
DROP TABLE #holdItems
-----------------------------------------------------------------------------------
--cursors
-----------------------------------------------------------------------------------
SELECT getdate() -- get time before the code is run
--temporary table to hold the procedures as we loop through
CREATE TABLE #holdProcedures
(
specific_name sysname
)
DECLARE @cursor CURSOR, --cursor variable
@c_routineName sysname -- variable to hold the values as we loop
SET @cursor = CURSOR FAST_FORWARD FOR SELECT DISTINCT specific_name
FROM information_schema.parameters
OPEN @cursor --activate the cursor
FETCH NEXT FROM @cursor INTO @c_routineName --get the first row
WHILE @@fetch_status = 0 --this means that the row was fetched cleanly
BEGIN
--check to see if the count of parameters for this specific name
--is between 2 and 3
IF ( SELECT count(*)
FROM information_schema.parameters as parameters
WHERE parameters.specific_name = @c_routineName )
BETWEEN 2 AND 3
BEGIN --it was, so put into temp storage
INSERT INTO #holdProcedures
VALUES (@c_routineName)
END
FETCH NEXT FROM @cursor INTO @c_routineName --get the next row
END
SELECT count(*)
FROM #holdProcedures
SELECT getdate() --output the time after the code is complete
go
-----------------------------------
SELECT GETDATE() --again for demo purposes
SELECT COUNT(*)
--use a nested subquery to get all of the functions with
--the proper count of parameters
FROM (SELECT parameters.specific_name
FROM information_schema.parameters AS parameters
GROUP BY parameters.specific_name
HAVING COUNT(*) BETWEEN 2 AND 3) AS counts
SELECT GETDATE()
-----------------------------------------------------------------------------------
--uses of cursors
-----------------------------------------------------------------------------------
--not in text, but there was already an item table
DROP TABLE item
go
-- table to demonstrate cursors
CREATE TABLE item
(
itemId int IDENTITY
CONSTRAINT XPKItem PRIMARY KEY,
sortOrderId int
CONSTRAINT xAKItem_sortOrder UNIQUE
)
-----------------------------------
DECLARE @holdSortOrderId int, @counter int
SET @counter = 1 --initialize counter
WHILE @counter <= 5
BEGIN
--use random numbers between 0 and 1000
SET @holdSortOrderId = CAST(RAND() * 1000 AS int)
--make sure the random number doesn't already exist as
--a sort order
IF NOT EXISTS (SELECT *
FROM dbo.item
WHERE sortOrderId = @holdSortOrderId)
BEGIN
--insert it
INSERT INTO dbo.item (sortOrderId)
VALUES (@holdSortOrderId)
--increment the counter
SET @counter = @counter + 1
END
END
-----------------------------------
SELECT *
FROM dbo.item
ORDER BY sortOrderId
go
-----------------------------------
DECLARE @cursor CURSOR, --cursor variable
@c_itemId int, @c_sortOrderId int, --cursor item variables
@currentSortOrderId int --used to increment the sort order
SET @currentSortOrderId = 1 --initialize the counter
--use static cursor so we do not see changed values
SET @cursor = CURSOR FORWARD_ONLY STATIC FOR SELECT itemId, sortOrderId
FROM dbo.item
ORDER BY sortOrderId
OPEN @cursor --activate the cursor
--get the first row
FETCH NEXT FROM @cursor INTO @c_itemId, @c_sortOrderId
--fetch_status = 0 says that the fetch went fine
WHILE @@fetch_status = 0 --this means that the row was fetched cleanly
BEGIN
--update the table to the new value of the sort order
UPDATE dbo.item
SET sortOrderId = @currentSortOrderId
WHERE itemId = @c_itemId
--increment the sort order counter to add 100 items of space
SET @currentSortOrderId = @currentSortOrderId + 100
--left out of text
SELECT @c_itemId as c_itemId, @c_sortOrderId as c_sortOrderId, @currentsortOrderId as currentsortOrderId
--get the next row
FETCH NEXT FROM @cursor INTO @c_itemId, @c_sortOrderId
END
go
-----------------------------------
SELECT *
FROM dbo.item
ORDER BY sortOrderId
go
-----------------------------------------------------------------------------------
--Nulls
-----------------------------------------------------------------------------------
SELECT CASE WHEN NOT(1=NULL) THEN 'True' ELSE 'False' END
go
-----------------------------------
SELECT CASE WHEN NOT(NOT(1=NULL)) THEN 'True' ELSE 'False' END
go
-----------------------------------
SELECT CASE WHEN (NOT((1=1) OR (1=NULL)) AND (1=1))
THEN 'True'
ELSE 'False'
END
go
declare @field varchar(20)
set @field = null
SELECT '*' + @field + '*'
SELECT CASE @field
WHEN NULL THEN ''
ELSE @field
END
SELECT ISNULL(@field,'')
SELECT COALESCE(@field,'')
go
-----------------------------------------------------------------------------------
--Views as encapsulation devices
-----------------------------------------------------------------------------------
--yes, again there already is an item table
drop table item
go
--items that we sell
CREATE TABLE item
(
itemId int NOT NULL IDENTITY,
name varchar(60) NOT NULL,
price money
)
--records sales
CREATE TABLE sale
(
saleId int NOT NULL IDENTITY,
itemId int NOT NULL, --foreign key to the item table
date datetime NOT NULL,
itemCount int NOT NULL --number of items sold
)
go
-----------------------------------
CREATE VIEW v_sale
AS
SELECT sale.saleId, sale.itemId, sale.date, sale.itemCount,
item.name, item.price
FROM dbo.sale AS sale
JOIN dbo.item AS item
ON sale.itemId = item.itemId
go
-----------------------------------------------------------------------------------
--Views in Real-Time Reporting
-----------------------------------------------------------------------------------
CREATE VIEW v_saleHourlyReport
AS
SELECT item.itemId, dbo.date$removeTime(sale.date) AS saleDate,
datePart(hour,sale.date) AS saleHour,
sum(sale.itemCount) AS totalSold,
sum(sale.itemCount * item.price) AS soldValue
FROM dbo.item as item (readuncommitted)
JOIN dbo.sale as sale(readuncommitted)
ON sale.itemId = item.itemId
--group by item ID information, then the day and the hour of the day, to
--give what was asked
GROUP BY item.itemId, item.name, dbo.date$removeTime(sale.date),
datePart(hour,sale.date)
-----------------------------------------------------------------------------------
--Views as security mechanisms
-----------------------------------------------------------------------------------
CREATE TABLE person
(
personId int IDENTITY,
firstName varchar(20) ,
lastName varchar(40)
)
go
-----------------------------------
CREATE VIEW vPerson
AS
SELECT personId, firstName, lastName
FROM dbo.person
go
-----------------------------------
CREATE VIEW v_saleHourlyReport_socksOnly
AS
SELECT itemId, saleDate, saleHour, totalSold, soldValue
FROM dbo.v_saleHourlyReport
WHERE itemId = 1
go
-----------------------------------------------------------------------------------
--Indexed Views
-----------------------------------------------------------------------------------
CREATE VIEW v_itemSale
WITH SCHEMABINDING
AS
SELECT item.itemId, item.name, sum(sale.itemCount) AS soldCount,
sum(sale.itemCount * item.price) AS soldValue
FROM dbo.item
JOIN dbo.sale
ON item.itemId = sale.itemId
GROUP BY item.itemId, item.name
GO
-----------------------------------
--NOTE: This index cannot be created without the Enterprise Edition
CREATE INDEX XV_itemSale_materialize
ON v_itemSale (itemId, name, soldCount, soldValue)
-----------------------------------
CREATE VIEW v_itemNoPrice
AS
SELECT itemId, name
FROM dbo.item
go
-----------------------------------------------------------------------------------
--DISTRIBUTED PARTITIONED VIEWS
-----------------------------------------------------------------------------------
CREATE TABLE sale_itemA
(
saleId int NOT NULL,
itemId int NOT NULL
CONSTRAINT chk$sale_itemA$itemId$One CHECK (itemId = 1),
itemCount int NOT NULL,
)
CREATE TABLE sale_itemB
(
saleId int NOT NULL,
itemId int NOT NULL
CONSTRAINT chk$sale_itemB$itemId$One CHECK (itemId = 2),
itemCount int NOT NULL
)
go
-----------------------------------
CREATE VIEW v_sale
AS
SELECT saleId, itemId, itemCount
FROM dbo.sale_itemA
UNION ALL -- no sort or duplicate removal
SELECT saleId, itemId, itemCount
FROM dbo.sale_itemB
go
-----------------------------------------------------------------------------------
--Stored Procedure Return Values
-----------------------------------------------------------------------------------
CREATE PROCEDURE returnValue$test
(
@returnThis int = 0
)
AS
RETURN @returnThis
go
-----------------------------------
DECLARE @returnValue int
EXEC @returnValue = returnValue$test @returnThis = 0
SELECT @returnValue AS returnValue
go
-----------------------------------
CREATE PROCEDURE caller$testreturnvalue
(
@testValue int
)
AS
DECLARE @returnValue int
EXEC @returnValue = returnValue$test @testValue
SELECT @returnValue AS returnValue
IF @returnValue < 0 --negative is bad
BEGIN
SELECT 'An error has occurred: ' + CAST(@returnValue AS varchar(10))
AS status
END
ELSE -- positive or zero is good
BEGIN
SELECT 'Call succeeded: ' + CAST(@returnValue AS varchar(10))
AS status
END
GO
-----------------------------------
EXEC caller$testreturnvalue -10
go
-----------------------------------------------------------------------------------
-- Result Sets
-----------------------------------------------------------------------------------
CREATE PROCEDURE test$statement
AS
SELECT 'Hi' AS hiThere
SELECT 'Bye' AS byeThere
GO
-----------------------------------
EXEC test$statement
go
-----------------------------------------------------------------------------------
--Error Handling
-----------------------------------------------------------------------------------
EXEC dbo.doesntExist
go
-----------------------------------
SELECT error, description
FROM master.dbo.sysmessages
WHERE error = 2812
go
-----------------------------------
RAISERROR 911911911 'This is a test message'
go
-----------------------------------
CREATE PROCEDURE test$validateParm
(
@parmValue int
) AS
IF @parmValue < 0
BEGIN
DECLARE @msg varchar(100)
SET @msg = 'Invalid @parmValue: ' + CAST(@parmValue AS varchar(10)) +
'. Value must be non-negative.'
RAISERROR 50000 @msg
RETURN -100
END
SELECT 'Test successful.'
RETURN 0
GO
----------------------------------------
exec dbo.test$validateParm 0
exec dbo.test$validateParm -1
go
-----------------------------------
--not in text
drop table test
go
CREATE TABLE test
(
testId int IDENTITY,
name varchar(60) NOT NULL
CONSTRAINT AKtest_name UNIQUE
)
go
-----------------------------------
CREATE PROCEDURE test$ins
(
@name varchar(60)
) AS
INSERT INTO dbo.test(name)
VALUES(@name)
IF @@error <> 0
BEGIN
-- raise an error that tells the user what has just occurred.
RAISERROR 50000 'Error inserting into test table'
END
GO
-----------------------------------
EXEC dbo.test$ins @name = NULL
-----------------------------------------------------------------------------------
-- Constraint Mapping
-----------------------------------------------------------------------------------
ALTER TABLE dbo.test
ADD CONSTRAINT chkTest$name$string$notEqualToBob
CHECK (name <> 'Bob')
go
-----------------------------------
INSERT INTO dbo.test (name)
VALUES ('Bob')
go
-----------------------------------
EXEC sp_addextendedproperty @name = 'ErrorMessage',
@value =
'The name column may not store a value of ''Bob''',
@level0type = 'User', @level0name = 'dbo',
@level1type = 'table', @level1name = 'test',
@level2type = 'constraint', @level2name =
'chkTest$name$string$notEqualToBob'
go
-----------------------------------
SELECT value AS message
FROM ::FN_LISTEXTENDEDPROPERTY('ErrorMessage', 'User', 'dbo', 'table', 'test',
'constraint', 'chkTest$name$string$notEqualToBob')
go
-----------------------------------------------------------------------------------
--Tagging Error Messages
-----------------------------------------------------------------------------------
CREATE PROCEDURE test$errorMessage
(
@key_testId int
) AS
--declare variable used for error handling in blocks
DECLARE @error int, --used to hold error value
@msg varchar(255), --used to preformat error messages
@msgtag varchar(255) --used to hold the tags for the error message
--set up the error message tag
SET @msgTag = '<' + object_name(@@procid) + ';type=P'
+ ';keyvalue=' + '@key_routineId:'
+ CONVERT(varchar(10),@key_testId)
--call to some stored procedure or modification statement on some table
--get the rowcount and error level for the error handling code
SELECT @error = 100 --simulated error
IF @error != 0 --an error occurred outside this procedure
BEGIN
SELECT @msg = 'A problem occurred calling the nonExistentProcedure. ' +
@msgTag + ';call=(procedure nonExistentProcedure)>'
RAISERROR 50000 @msg
RETURN -100
END
GO
-----------------------------------
test$errorMessage @key_testId = 10
go
-----------------------------------------------------------------------------------
-- Constraint Mapping
-----------------------------------------------------------------------------------
CREATE PROCEDURE tranTest$inner
AS
BEGIN TRANSACTION
--code finds an error, decides to rollback
ROLLBACK TRANSACTION
RETURN -100
go
CREATE PROCEDURE tranTest$outer
AS
DECLARE @retValue int
BEGIN TRANSACTION
EXEC @retValue = tranTest$inner
IF @retValue < 0
BEGIN
ROLLBACK TRANSACTION
RETURN @retValue
END
COMMIT TRANSACTION
go
-----------------------------------
EXEC tranTest$outer
-----------------------------------
--changed to alter
ALTER PROCEDURE tranTest$inner
AS
DECLARE @tranPoint sysname --the data type of identifiers
SET @tranPoint = object_name(@@procId) + CAST(@@nestlevel AS varchar(10))
BEGIN TRANSACTION
SAVE TRANSACTION @tranPoint
--again doesn't do anything for simplicity
ROLLBACK TRANSACTION @tranPoint
COMMIT TRANSACTION
RETURN -100
GO
--changed to alter
ALTER PROCEDURE tranTest$outer
AS
DECLARE @retValue int
DECLARE @tranPoint sysname --the data type of identifiers
SET @tranPoint = object_name(@@procId) + CAST(@@nestlevel AS varchar(10))
BEGIN TRANSACTION
SAVE TRANSACTION @tranPoint
EXEC @retValue = tranTest$inner
IF @retValue < 0
BEGIN
ROLLBACK TRANSACTION @tranPoint
COMMIT TRANSACTION
RETURN @retvalue
END
COMMIT TRANSACTION
GO
-----------------------------------
EXEC tranTest$outer
-----------------------------------------------------------------------------------
-- Common Practices with Stored Procedures
-----------------------------------------------------------------------------------
CREATE TABLE routine
(
routineId int NOT NULL IDENTITY CONSTRAINT PKroutine PRIMARY KEY,
name varchar(384) NOT NULL CONSTRAINT akroutine_name UNIQUE,
description varchar(100) NOT NULL,
timestamp timestamp
)
-----------------------------------
--database name changed to master.
INSERT INTO routine (name, description)
SELECT specific_catalog + '.' + specific_schema + '.' + specific_name,
routine_type + ' in the ' + specific_catalog + ' database created on ' +
CAST(created AS varchar(20))
FROM master.information_schema.routines
SELECT count(*) FROM routine
-----------------------------------------------------------------------------------
-- Retrieve
-----------------------------------------------------------------------------------
CREATE PROCEDURE routine$list
(
@routineId int = NULL, --primary key to retrieve single row
@name varchar(60) = '%', --like match on routine.name
@description varchar(100) = '%' --like match on routine.description
)
-- Description : gets routine records for displaying in a list
-- :
-- Return Val : nonnegative: success
-- : -1 to -99: system generated return value on error
-- : -100: generic procedure failure
AS
-- as the count messages have been known to be a problem for clients
SET NOCOUNT ON
-- default the @name parm to '%' if the passed value is NULL
IF @name IS NULL SELECT @name = '%'
-- default the @description parm to '%' if the passed value is NULL
IF @description IS NULL SELECT @description = '%'
--s elect all of the fields (less the timestamp) from the table for viewing.
SELECT routine.routineId AS routineId, routine.name AS name,
routine.description AS description
FROM dbo.routine AS routine
WHERE (routine.routineId = @routineId
OR @routineId IS NULL)
AND (routine.name LIKE @name)
AND (routine.description LIKE @description)