-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path03-Transactions.sql
85 lines (73 loc) · 2.42 KB
/
03-Transactions.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
-- No transaction
BEGIN TRY
INSERT INTO SalesLT.SalesOrderHeader (DueDate, CustomerID, ShipMethod)
VALUES
(DATEADD(dd, 7, GETDATE()), 1, 'STD DELIVERY');
DECLARE @SalesOrderID int = SCOPE_IDENTITY();
INSERT INTO SalesLT.SalesOrderDetail (SalesOrderID, OrderQty, ProductID, UnitPrice, UnitPriceDiscount)
VALUES
(@SalesOrderID, 1, 99999, 1431.50, 0.00);
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
END CATCH;
-- View orphaned orders
SELECT h.SalesOrderID, h.DueDate, h.CustomerID, h.ShipMethod, d.SalesOrderDetailID
FROM SalesLT.SalesOrderHeader AS h
LEFT JOIN SalesLT.SalesOrderDetail AS d
ON d.SalesOrderID = h.SalesOrderID
WHERE D.SalesOrderDetailID IS NULL;
-- Manually delete orphaned record
DELETE FROM SalesLT.SalesOrderHeader
WHERE SalesOrderID = SCOPE_IDENTITY();
-- Use a transaction
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO SalesLT.SalesOrderHeader (DueDate, CustomerID, ShipMethod)
VALUES
(DATEADD(dd, 7, GETDATE()), 1, 'STD DELIVERY');
DECLARE @SalesOrderID int = SCOPE_IDENTITY();
INSERT INTO SalesLT.SalesOrderDetail (SalesOrderID, OrderQty, ProductID, UnitPrice, UnitPriceDiscount)
VALUES
(@SalesOrderID, 1, 99999, 1431.50, 0.00);
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
PRINT XACT_STATE();
ROLLBACK TRANSACTION;
END
PRINT ERROR_MESSAGE();
THROW 50001,'An insert failed. The transaction was cancelled.', 0;
END CATCH;
-- Check for orphaned orders
SELECT h.SalesOrderID, h.DueDate, h.CustomerID, h.ShipMethod, d.SalesOrderDetailID
FROM SalesLT.SalesOrderHeader AS h
LEFT JOIN SalesLT.SalesOrderDetail AS d
ON d.SalesOrderID = h.SalesOrderID
WHERE D.SalesOrderDetailID IS NULL
-- Use XACT_ABORT
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO SalesLT.SalesOrderHeader (DueDate, CustomerID, ShipMethod)
VALUES
(DATEADD(dd, 7, GETDATE()), 1, 'STD DELIVERY');
DECLARE @SalesOrderID int = SCOPE_IDENTITY();
INSERT INTO SalesLT.SalesOrderDetail (SalesOrderID, OrderQty, ProductID, UnitPrice, UnitPriceDiscount)
VALUES
(@SalesOrderID, 1, 99999, 1431.50, 0.00);
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
THROW 50001,'An insert failed. The transaction was cancelled.', 0;
END CATCH;
SET XACT_ABORT OFF;
-- Check for orphaned orders
SELECT h.SalesOrderID, h.DueDate, h.CustomerID, h.ShipMethod, d.SalesOrderDetailID
FROM SalesLT.SalesOrderHeader AS h
LEFT JOIN SalesLT.SalesOrderDetail AS d
ON d.SalesOrderID = h.SalesOrderID
WHERE D.SalesOrderDetailID IS NULL