การเขียน DO statement
ในการทำความสะอาดข้อมูล มักพบข้อมูลที่มีวันที่ผิดรูปแบบอยู่เสมอ ซึ่งจะทำให้เกิด exception และหยุดการทำงานของ SQL statement แต่หากใช้ฟังก์ชัน DO ร่วมกับ exception handler คำสั่งจะสามารถทำงานจนเสร็จสมบูรณ์ได้ มาดูกันว่าจะจัดการ exception ประเภทนี้กับตาราง patients และคอลัมน์ created_on ได้อย่างไร พร้อมกับฝึกใช้ฟังก์ชันแบบ DO ไปด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transactions and Error Handling in PostgreSQL
คำแนะนำการฝึกหัด
- สร้างฟังก์ชัน
DOเพื่อเริ่มต้นการดักจับ exception - BEGIN transaction โดย
INSERTแถวข้อมูล (a1c=5.8,glucose=89,fasting=TRUEและcreated_on= '37-03-2020 01:15:54') ลงในตาราง patients - เพิ่ม
EXCEPTIONhandler ที่จะ insert'bad date'ลงในคอลัมน์detailของตารางerrorsเมื่อเกิดข้อผิดพลาด - ระบุภาษาเป็น
'plpgsql'
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
-- Create a DO $$ function
____ ____
-- BEGIN a transaction block
BEGIN
INSERT INTO patients (a1c, glucose, fasting, created_on)
VALUES (____, ____, ____, '37-03-2020 01:15:54');
-- Add an EXCEPTION
___
-- For all all other type of errors
WHEN others THEN
INSERT INTO errors (msg, detail)
VALUES ('failed to insert', '____');
END;
-- Make sure to specify the language
$$ language '____';
-- Select all the errors recorded
SELECT * FROM errors;