标签:
CREATE TABLE STUDENT( --创建学生表
ID NUMBER(10) PRIMARY KEY, --主键ID
NAME VARCHAR2(20),
CLASSNAME VARCHAR2(20) --班级ID
);
CREATE SYNONYM STU FOR STUDENT; --给学生表STUDENT创建别名(同义词)
INSERT INTO STUDENT VALUES(1,‘Tom‘,1);
INSERT INTO STUDENT VALUES(2,‘Jack‘,1);
INSERT INTO STUDENT VALUES(3,‘Bay‘,2);
INSERT INTO STUDENT VALUES(4,‘John‘,3);
INSERT INTO STUDENT VALUES(5,‘Dld‘,2);
INSERT INTO STUDENT VALUES(6,‘Fmhn‘,4);
INSERT INTO STUDENT VALUES(7,‘Ecls‘,3);
INSERT INTO STUDENT VALUES(9,‘Wsms‘,3);
INSERT INTO STUDENT VALUES(8,‘Qmndk‘,4);
--以上是添加数据 还没有常见触发器和序列的时候 ID不能自动增长 所以要不能写null 要明确指定---
DELETE STUDENT; --删除学生表的所有数据
ALTER TABLE STUDENT RENAME COLUMN NAME TO SNAME; --把学生表中列名为‘NAME’的列的名字 改为‘SNAME’
SELECT * FROM STUDENT; --查询学生表所以的数据
CREATE TABLE CLASSTAB( --创建班级表
CLASSID NUMBER(2) PRIMARY KEY, --班级ID
CNAME VARCHAR2(20)
);
INSERT INTO CLASSTAB VALUES(1,‘3G‘);
INSERT INTO CLASSTAB VALUES(2,‘SVSE‘);
INSERT INTO CLASSTAB VALUES(3,‘GIS‘);
INSERT INTO CLASSTAB VALUES(4,‘EM‘);
SELECT * FROM CLASSTAB; --查询班级表的所有数据
--创建视图
CREATE OR REPLACE VIEW V_SC
AS
SELECT s.SNAME,c.CNAME FROM STUDENT s LEFT JOIN CLASSTAB c ON s.CLASSNAME=c.CLASSID;--左链接
--调用视图
SELECT * FROM V_SC;
--创建函数 返回3G班的总人数
CREATE OR REPLACE FUNCTION FUN_NUM
(IN_CNAME IN CLASSTAB.CNAME%TYPE)
RETURN NUMBER
AS
OUT_NUM NUMBER;
BEGIN
IF IN_CNAME =‘3G‘ THEN
SELECT COUNT(CNAME) INTO OUT_NUM FROM V_SC WHERE CNAME=‘3G‘;
ELSIF IN_CNAME=‘SVSE‘ THEN
SELECT COUNT(CNAME) INTO OUT_NUM FROM V_SC WHERE CNAME=‘SVSE‘;
ELSIF IN_CNAME = ‘GIS‘ THEN
SELECT COUNT(CNAME) INTO OUT_NUM FROM V_SC WHERE CNAME=‘GIS‘;
ELSIF IN_CNAME = ‘EM‘ THEN
SELECT COUNT(CNAME) INTO OUT_NUM FROM V_SC WHERE CNAME = ‘EM‘;
END IF;
RETURN OUT_NUM;
END FUN_NUM;
--调用函数
SELECT DISTINCT FUN_NUM(‘GIS‘) AS 人数 from V_SC;
--创建存储过程 给学生表添加一条记录
CREATE OR REPLACE PROCEDURE PROCEDURE_ADD
(IN_ID IN STUDENT.ID%TYPE,IN_SNAME STUDENT.SNAME%TYPE,IN_CLASSNAME STUDENT.CLASSNAME%TYPE)
AS
BEGIN
INSERT INTO STUDENT VALUES(IN_ID,IN_SNAME,IN_CLASSNAME);
DBMS_OUTPUT.PUT_LINE(‘数据添加成功!‘);
END PROCEDURE_ADD;
--调用过程的时候 因为这是添加数据 所以添加完后 要commit提交 不然显示不了添加的数据
--在调用之前要SET SERVEROUT ON
EXECUTE PROCEDURE_ADD(NULL,‘AA‘,3);
--创建序列
CREATE SEQUENCE SEQ_STU
INCREMENT BY 1
START WITH 11
MAXVALUE 99999
MINVALUE 1;
--创建触发器 添加数据的时候id自增
CREATE OR REPLACE TRIGGER TIGGER_STU
BEFORE
INSERT ON STUDENT
FOR EACH ROW
WHEN(NEW.ID IS NULL)
BEGIN
SELECT SEQ_STU.NEXTVAL INTO:NEW.ID FROM DUAL;
END;
INSERT INTO STUDENT VALUES(NULL,‘AA‘,2);
--创建触发器 删除班级时 将该班级的所有学生信息也删除
CREATE OR REPLACE TRIGGER MYTRIGGER
AFTER DELETE
ON CLASSTAB
FOR EACH ROW
BEGIN
DELETE FROM STUDENT WHERE CLASSNAME = :old.CLASSID;
END;
--:old.CLASSID 是触发器操作的那种表 :old就相当于那张表 本例子中触发器操作的是CLASSTAB这张表 所以:old相当于CLASSSTAB这张表
DELETE FROM CLASSTAB WHERE CLASSID = 2;
SELECT * FROM STUDENT;
SELECT * FROM CLASSTAB;
关于oracle的函数,存储过程,触发器,序列,视图,左右连接一些的应用 带案例
标签:
原文地址:http://www.cnblogs.com/wenjie123/p/4522458.html