这一节主要包括以下内容:
- 视图
- 函数
- 触发器
一、视图
说明:
视图是一个伪表,可以便于用户执行如下操作:
- 它以自然和直观的方式构建数据,并使其易于查找。
- 它限制对数据的访问,使得用户只能看到有限的数据而不是完整的数据。
- 它归总来自各种表中的数据以生成报告。
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中生成了日志数据。