開始使用免費開始

撰寫 do 陳述式

在清理資料時,常會遇到含有錯誤日期的資料。這會導致拋出例外並中止 SQL 陳述式。不過,透過使用帶有例外處理器的 DO 函式,我們就能讓陳述式執行到完成。現在用 patients 資料表與 created_on 欄位,看看如何處理這類例外。這也讓我們有機會使用 DO 風格的函式。

本練習屬於課程

PostgreSQL 的交易與錯誤處理

檢視課程

練習說明

  • 建立一個 DO 函式來啟動例外攔截。
  • BEGIN 一個交易,將列(a1c = 5.8glucose = 89fasting = TRUE,以及 created_on = '37-03-2020 01:15:54'INSERT 進 patients。
  • 加入一個 EXCEPTION 處理器,在發生錯誤時把 'bad date' 插入 errors 資料表的 detail 欄位。
  • 指定語言為 '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;
編輯並執行程式碼