【學習筆記】PostgreSQL進階技巧之檢視、函式和觸發器
阿新 • • 發佈:2020-07-26
這一節主要包括以下內容:
- 檢視
- 函式
- 觸發器
一、檢視
說明:
檢視是一個偽表,可以便於使用者執行如下操作:
- 它以自然和直觀的方式構建資料,並使其易於查詢。
- 它限制對資料的訪問,使得使用者只能看到有限的資料而不是完整的資料。
- 它歸總來自各種表中的資料以生成報告。
1.1建立檢視
語法:
CREATE [TEMP | TEMPORARY] VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
示例:
create view current_employees as select name, id, salary from employees;
1.2檢視檢視
示例:
select * from current_employees;
結果:
1.3刪除檢視
語法:
DROP VIEW view_name;
示例:
drop view current_employees;
二、函式
說明:
PostgreSQL函式也稱為PostgreSQL儲存過程。 PostgreSQL函式或儲存過程是儲存在資料庫伺服器上並可以使用SQL介面呼叫的一組SQL和過程語句(宣告,分配,迴圈,控制流程等)。 它有助於您執行通常在資料庫中的單個函式中進行多次查詢和往返操作的操作。
語法:
CREATE [OR REPLACE] FUNCTION function_name (arguments) RETURNS return_datatype AS $variable_name$ DECLARE declaration; [...] BEGIN < function_body > [...] RETURN { variable_name | value } END; LANGUAGE plpgsql;
引數說明:
- function_name:指定函式的名稱
- [OR REPLACE]:是可選的,允許修改/替換現有函式
- RETURN:指定從函式的返回的資料型別
- function_body:包含可執行部分
- plpgsql:指定實現該函式的語言的名稱
示例:
create or replace function totalRecords () returns integer as $total$ declare total integer; begin select count(*) into total from EMPLOYEES; return total; end; $total$ language plpgsql;
輸出:
select totalRecords();
結果:
三、觸發器
說明:
觸發器是一組動作或資料庫回撥函式,它們在指定的表上執行指定的資料庫事件(即,INSERT,UPDATE,DELETE或TRUNCATE語句)時自動執行。 觸發器用於驗證輸入資料,執行業務規則,保持審計跟蹤等。
觸發器函式非常有用,待有必要學習時進行深入學習。
語法:
CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name
ON table_name
[
-- Trigger logic goes here....
];
引數說明:
- event_name可以是INSERT,UPDATE,DELETE和TRUNCATE
示例:
現在新建了company和audit兩張空表,使用觸發器函式自動在往company表中插入資料時往audit表中插入兩行資料用於檢測插入的狀態。
(1)建立新表:
create table company(
id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real);
create table audit(
emp_id int not null,
entry_date text not null);
(2)在COMPANY表上建立觸發器之前,首先建立一個名為auditlogfunc()的函式/過程。
create or replace function auditlogfunc() returns trigger as $example_table$
begin
insert into audit(emp_id,entry_date)values(new.id, current_timestamp);
return new;
end
$example_table$ language plpgsql;
(3)建立觸發器函式
create trigger example_trigger after insert on company
for each row execute procedure auditlogfunc();
(4)測試語句:
insert into company values(1, '小米科技', 8, '北京市朝陽區', 9999);
insert into company values(2, '京東中科', 6, '廣州市天河區', 8999);
結果:
說明:
此時在company表中插入資料後,自動在audit中生成了日誌資料。