DB2視圖是數據庫中的一個虛擬表,它是基于一個或多個實際表的查詢結果的表示
例如,假設我們有一個名為employees
的基表,我們想要創建一個名為employee_view
的視圖,該視圖包含員工的姓名和部門。我們可以創建一個觸發器,當employees
表中的數據發生變化時,觸發器會自動更新視圖:
CREATE TRIGGER update_employee_view
AFTER INSERT OR UPDATE OR DELETE ON employees
FOR EACH ROW
BEGIN
IF INSERTING THEN
-- 當插入新記錄時,更新視圖
EXECUTE IMMEDIATE 'CREATE OR REPLACE VIEW employee_view AS SELECT name, department FROM employees';
ELSIF UPDATING THEN
-- 當更新記錄時,重新構建視圖
EXECUTE IMMEDIATE 'DROP VIEW IF EXISTS employee_view';
EXECUTE IMMEDIATE 'CREATE VIEW employee_view AS SELECT name, department FROM employees';
ELSIF DELETING THEN
-- 當刪除記錄時,重新構建視圖
EXECUTE IMMEDIATE 'DROP VIEW IF EXISTS employee_view';
EXECUTE IMMEDIATE 'CREATE VIEW employee_view AS SELECT name, department FROM employees';
END IF;
END;
例如,我們可以創建一個名為update_employee_view
的存儲過程,用于更新employee_view
視圖:
CREATE OR REPLACE PROCEDURE update_employee_view AS
BEGIN
EXECUTE IMMEDIATE 'DROP VIEW IF EXISTS employee_view';
EXECUTE IMMEDIATE 'CREATE VIEW employee_view AS SELECT name, department FROM employees';
END;
當需要更新視圖時,只需調用此存儲過程即可:
CALL update_employee_view();
請注意,這些方法可能會導致性能問題,因為每次基表中的數據發生變化時,都需要重新構建視圖。在實際應用中,您需要根據具體需求選擇合適的方法。