forked from fissehab/T_SQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-Ensuring Data Consistency.sql
More file actions
42 lines (36 loc) · 991 Bytes
/
Copy path02-Ensuring Data Consistency.sql
File metadata and controls
42 lines (36 loc) · 991 Bytes
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
DECLARE @SalesOrderID int = 0
-- uncomment the following line to specify an existing order
-- SELECT @SalesOrderID = MIN(SalesOrderID) FROM SalesLT.SalesOrderHeader;
BEGIN TRY
IF NOT EXISTS (SELECT * FROM SalesLT.SalesOrderHeader
WHERE SalesOrderID = @SalesOrderID)
BEGIN
-- Throw a custom error if the specified order doesn't exist
DECLARE @error varchar(25);
SET @error = 'Order #' + cast(@SalesOrderID as varchar) + ' does not exist';
THROW 50001, @error, 0
END
ELSE
BEGIN
BEGIN TRANSACTION
DELETE FROM SalesLT.SalesOrderDetail
WHERE SalesOrderID = @SalesOrderID;
-- THROW 50001, 'Unexpected error', 0 --Uncomment to test transaction
DELETE FROM SalesLT.SalesOrderHeader
WHERE SalesOrderID = @SalesOrderID;
COMMIT TRANSACTION
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
-- Rollback the transaction and re-throw the error
ROLLBACK TRANSACTION;
THROW;
END
ELSE
BEGIN
-- Report the error
PRINT ERROR_MESSAGE();
END
END CATCH