1、
函数:必须有返回值,函数必须用基本数据类型
CREATE FUNCTION 函数的名字 ( 参数列表 )
RETURN TYPENAME
IS
变量的声明
BEGIN
过程语句
END
SELECT COMM + SAL FROM EMP;
CREATE OR REPLACE FUNCTION add_number (
p_comm number , p_sal number
)
RETURN number
IS
v_total number( 6,2 );
BEGIN
IF p_sal IS NULL AND p_comm IS NOT NULL THEN
v_total := p_comm ;
ELSIF p_sal IS NOT NULL AND p_comm IS NULL THEN
v_total := p_sal;
ELSE
v_total := p_comm + p_sal ;
END IF;
RETURN v_total;
END;
select add_number(comm , sal) ,
empno , ename from emp;
2、
包:和命名空间差不多 ERP( A1 A2 )
包头 包体
CREATE OR REPLACE PACKAGE pkg_A1
IS
FUNCTION add_number (
p_comm number , p_sal number
) RETURN number ;
PROCEDURE USP_GETSAL2
( i_deptno IN NUMBER , io_sal IN OUT NUMBER );
END;
--创建包体
CREATE OR REPLACE PACKAGE BODY pkg_A1
IS
FUNCTION add_number (
p_comm number , p_sal number
)
RETURN number
IS
v_total number( 6,2 );
BEGIN
IF p_sal IS NULL AND p_comm IS NOT NULL THEN
v_total := p_comm ;
ELSIF p_sal IS NOT NULL AND p_comm IS NULL THEN
v_total := p_sal;
ELSE
v_total := p_comm + p_sal ;
END IF;
RETURN v_total;
END add_number;
PROCEDURE USP_GETSAL2
( i_deptno IN NUMBER , io_sal IN OUT NUMBER )
IS
v_sal EMP.SAL%TYPE := 0.0;
BEGIN
v_sal := io_sal;
DBMS_OUTPUT.PUT_LINE( v_sal);
SELECT AVG( SAL ) INTO io_sal FROM EMP
WHERE DEPTNO = i_deptno;
END USP_GETSAL2;
END pkg_A1;
--调用方式是一样的,只不过前面加包名.对象调用
3、
--触发器
触发器就是特殊的存储过程,特殊在如下几点:
(1) 不是显式调用,不是由程序员调用他的
(2)触发器没有参数
触发器可以分为DML ( BEFORE , AFTER , INSTEADOF |
INSERT , UPDATE , DELETE)和DDL触发
CREATE OR REPLACE TRIGGER trg_触发器名字
[触发的时机BEFORE , AFTER , INSTEADOF]
| [INSERT , UPDATE DELETE] ON 表名
触发级别[FOR EACH ROW]
BEGIN
语句
END;
create table sales
(
sid number(4) primary key,
gid number(4) ,
snumber number(4)
)
create table goods
(
gid number(4) primary key,
gname varchar2(100),
total number(4)
)
insert into goods values(1001 , '大白菜' , 100);
commit;
--((1)). 卖2斤白菜,那就是新增sales表,更新goods表
insert into sales values(1 , 1001 , 2);
commit;
select * from goods;
CREATE OR REPLACE TRIGGER trg_insert_sales
AFTER INSERT ON sales FOR EACH ROW
BEGIN
UPDATE goods SET total = total - :NEW.snumber
WHERE gid = :NEW.GID ;
END;
((2))幽灵表
:NEW(存储的是我新添加的数据)
:OLD(存储的是我删除的数据)
更新的数据存储在什么地方?更新之前数据在:OLD
里面存储,更新之后的数据在:NEW里面存储
--((3)) 卖2斤白菜,更新goods表,新增sales表
update goods set total = 98 where gid = 1001;
伪代码:
insert into sales values( seq.nextVal , :OLD.gid , :OLD.total - :NEW.total
)
-- 触发器实现自增序列
create table t02
(
tid number(4) primary key, --这一列是自增列
tname varchar2(100)
)
create sequence seq_t02;
CREATE OR REPLACE TRIGGER trg_insert_t02
BEFORE INSERT ON t02 FOR EACH ROW
BEGIN
:NEW.tid := seq_t02.nextVal;
END;
insert into t02(tname) values('张三丰');
commit;
select * from t02;
标签:触发器,NULL,END,函数,sal,number,comm,oracle,total From: https://blog.51cto.com/u_12528551/5900085