Doomed transactions
ต้องการแทรกข้อมูลลูกค้าใหม่ 2 รายลงในตาราง customer จึงเตรียมสคริปต์ที่ควบคุมให้ transaction rollback และแสดงข้อความแจ้งข้อผิดพลาดเมื่อเกิดปัญหาขึ้น โดยใช้ XACT_ABORT ร่วมกับ XACT_STATE
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transactions and Error Handling in SQL Server
คำแนะนำการฝึกหัด
- ตั้งค่า
XACT_ABORTให้เหมาะสม - ตรวจสอบว่ามี transaction ที่เปิดอยู่หรือไม่
- Rollback transaction
- เลือกข้อความแจ้งข้อผิดพลาด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
-- Use the appropriate setting
SET XACT_ABORT ___;
BEGIN TRY
BEGIN TRAN;
INSERT INTO customers VALUES ('Mark', 'Davis', '[email protected]', '555909090');
INSERT INTO customers VALUES ('Dylan', 'Smith', '[email protected]', '555888999');
COMMIT TRAN;
END TRY
BEGIN CATCH
-- Check if there is an open transaction
IF ___() <> 0
-- Rollback the transaction
___;
-- Select the message of the error
SELECT ___() AS Error_message;
END CATCH