test


title: Java数据库note
toc: true
comments: true
tags: Java
abbrlink: 21e432e7
date: 2021-08-01 15:51:50

categories:

这里记录的是对数据库的学习 !

[TOC]

chpt01 数据库基础

chpt02 基础查询和排序

-- DQL : Data Query Language

--select 基本查询
    select * from EMPLOYEES

--1. 查询结构
     select *|列 -- 限定列
     from 表/视图
     where 限定条件 -- 限定行
     group by 
     having                 -- 限定组
     order by 列|序号

--2. 限定列查询-基本查询
     select employee_id, first_name,last_name,salary from EMPLOYEES

--3. 限定行查询
     select employee_id, first_name,last_name,salary from EMPLOYEES where salary >= 15000

--4. 操作符
     --4.1 别名 as(给表取别名不能用as,别名用双引号,字符串用单引号)
     select employee_id as "雇员ID", first_name "名字",last_name "姓",salary 月薪 from EMPLOYEES e
         select employee_id as "雇员 ID" , first_name "名 字",last_name "姓",salary 月薪 from EMPLOYEES e

     --4.2 算数:+ - * / mod(m,n)
     select e.salary 原有月薪, e.salary + 600 月薪 from employees e where employee_id = 200;

     --4.3 关系:> >= < <= = != <> ^=
     select * from EMPLOYEES where salary >= 15000

     --4.4 逻辑:and or not
     select first_name, last_name, salary from employees where salary >= 10000 and salary <= 15000
         select first_name, last_name, salary from employees where salary <3000 or salary > 15000

     --4.5 between...and..
     select first_name, last_name, salary from employees where salary between 10000 and 15000
         select first_name, last_name, salary from employees where salary >= 10000 and salary <= 15000

     --4.6 in(v1,v2,..,vN)
     select first_name, last_name, salary from employees where salary in(10000,6000)
         select first_name, last_name, salary from employees where salary = 10000 or salary = 6000

     --4.7 like(% _) escape
     select first_name, last_name, salary from employees where first_name like '%a%'
     select first_name, last_name, salary from employees where first_name like 'D_n%'

     --4.8 is (not) null
     select * from employees where COMMISSION_PCT is not null

     --4.9 || concat()
         select first_name || ' ' || last_name 姓名, salary 薪酬 from employees
     select concat(concat(first_name,' '),last_name) 姓名, salary 薪酬 from employees

     --4.10 distinct 去重
     select distinct salary from employees

     --4.11 union(all不去重) /intersect/minus
         select EMPLOYEE_ID,SALARY from employees where salary > 2700 and salary < 3000
     union
         select EMPLOYEE_ID,SALARY from employees where salary > 2800 and salary < 3100

         select EMPLOYEE_ID,SALARY from employees where salary > 2700 and salary < 3000
     minus
         select EMPLOYEE_ID,SALARY from employees where salary > 2800 and salary < 3100

     select EMPLOYEE_ID,SALARY from employees where salary > 2700 and salary < 3000
     intersect
         select EMPLOYEE_ID,SALARY from employees where salary > 2800 and salary < 3100
--5. 排序:asc(升序) desc(降序)
     -- 按月薪降序排列
     select EMPLOYEE_ID,SALARY from employees order by salary desc
     select EMPLOYEE_ID,SALARY from employees order by 2 desc

     -- 按月薪降序排列,月薪相同的雇员再按雇员ID排列
         select EMPLOYEE_ID,SALARY from employees order by salary desc,EMPLOYEE_ID asc




chpt03 函数

--函数

  --1. 字符串
    select length('abc'),upper('abc') from dual; 
  select substr('hello',2),substr('hello',2,2) from dual;

  --2. 数字
  select abs(-2), round(12.56),round(12.56,1),round(12.56,-1),round(16.56,-1) from dual;

  --3. 日期
  select sysdate,add_months(sysdate,5) from dual;

  --4. 转换函数:
       --字符串 to 数字: to_number() 
       select to_number('123')+1 from dual;
       select '123'+1 from dual;

       --字符串 to 日期: to_date()
       select to_date('2021/04/05','YYYY/MM/DD')+1 from dual;

       --数字或日期 to 字符串: to_char() 
       select length(to_char(123)),to_char(sysdate,'yyyy-mm-dd hh24:mm:ss') from dual;


  --5. 分组函数
       select 
                    count(*) 雇员数量, 
                    max(e.SALARY) 最高月薪,
                    min(e.SALARY) 最低月薪,
                    avg(e.SALARY)   平均月薪,
                    sum(e.SALARY)   总薪酬
       from employees e;

  --6. 通用函数
       --nvl
             select nvl(e.COMMISSION_PCT,0) * e.SALARY from EMPLOYEES e;
             select nvl2(e.COMMISSION_PCT,e.COMMISSION_PCT,0) * e.SALARY from EMPLOYEES e;

       --decode
       select decode(1,1,'星期一',2,'星期二',3,'星期三','数据有误') from dual;

       --case when then end
       select e.SALARY,
                        case 
                                when e.SALARY < 5000  then '温饱'
                            when e.SALARY BETWEEN 5000 and 10000 then '小康'
                                when e.SALARY > 10000  then '滋润'
                        end 工资状况
             from EMPLOYEES e;

             select e.SALARY,
                        case e.SALARY
                                when 5000  then '温饱'
                            when 6000 then '小康'
                                when 10000  then '滋润'
                else '一般'
                        end 工资状况
             from EMPLOYEES e;




chpt04 多表查询

--多表查询

/* 一、内连接:只查询出符合连接条件的数据 */

  --1. 等值连接: where =
  select s.*,SC.score from student s, score sc where s.no = SC.no

  --2. 等值连接:join on
    select s.*,SC.score from student s join score sc on s.no = SC.no

  --3. 等值连接:natural join
  select * from student natural join score

  --4. 等值连接:join using
    select * from student join score using(no)

  --5. 非等值连接
     select s.*,SC.score,sg.grade
   from student s, score sc , score_grade sg
     where s.no = SC.no and SC.score between sg.min_score and sg.max_score

     select s.*,SC.score
   from (student s join score sc on s.no = SC.no), score_grade sg
     where SC.score between sg.min_score and sg.max_score


/* 二、外连接 :不仅查询出符合连接条件的数据,还查询出不符合连接条件的数据*/
   --1. left [outer] join
   select s.*,SC.* from student s left join score sc on s.no = SC.no

   --2. right [outer] join
     select s.*,SC.* from student s right join score sc on s.no = SC.no

   --3. full [outer] join (mysql 不支持full join)
   select s.*,SC.* from student s full join score sc on s.no = SC.no

   --4. 笛卡尔集
   select * from student,score;



chpt05 子查询&分组查询

-- 子查询(内查询)
  -- 1. 单行(> >= < <= = != <> )
  select e.first_name, e.salary from employees e 
  where e.salary > (
        select salary from employees e where e.employee_id = 145
  )

  -- 2. 多行(all any)
  select e.first_name, e.salary from employees e 
  where e.salary >all (
        select e.salary from employees e where e.employee_id in(198,199,200,201)
  )

  select e.first_name, e.salary from employees e 
  where e.salary >any (
        select e.salary from employees e where e.employee_id in(198,199,200,201)
  )

  -- >all 等价于 >max()
  select e.first_name, e.salary from employees e 
  where e.salary > (select max(e.salary) from employees e where e.employee_id in(198,199,200,201))

  -- >any 等价于 >min()
  select e.first_name, e.salary from employees e 
  where e.salary > (select min(e.salary) from employees e where e.employee_id in(198,199,200,201))

  -- * 子查询可以出现的位置
    -- select
       select (select sysdate from dual) from dual
    -- from
       select * from (select * from employees)
    -- where
    -- having 

-- 分组查询: group by ... having
    select max(e.salary) 最高薪酬,
      min(e.salary) 最低薪酬,
      avg(e.salary) 平均薪酬,
      sum(e.salary) 总薪酬,
      count(e.salary) 人数
    from employees e;

    -- select 后面出现的字段,只能是group by后面出现过的字段
    select e.department_id 部门,
      max(e.salary) 最高薪酬,
      min(e.salary) 最低薪酬,
      avg(e.salary) 平均薪酬,
      sum(e.salary) 总薪酬,
      count(e.salary) 人数
    from employees e
    group by e.department_id
    order by e.department_id

    -- having: 限定组
    select e.department_id 部门,
      max(e.salary) 最高薪酬,
      min(e.salary) 最低薪酬,
      avg(e.salary) 平均薪酬,
      sum(e.salary) 总薪酬,
      count(e.salary) 人数
    from employees e
    group by e.department_id
    having count(e.salary) >= 3

chpt06 DML&TCL

-- DQL : select
   select * from student;
   select * from student_log;   

-- DML : insert 、 delete 、 update
    -- 1 insert 增
        -- 1.1 insert into values
        insert into student_log(no,name,idcard,sex,age) 
        values('2002','libai',null,1,20)

        -- 1.2 insert into select
        insert into student_log(no,name,idcard,sex,age)
        select no,name,idcard,sex,age from student where no = '1001';

    -- 2 delete 删
        -- 2.1 delete from 表名
        delete from student_log where no = '2002'

        -- 2.2 delete 表名 (仅oralce支持)
        delete student_log where no = '2002'

    -- 3 update 改
        -- 3.1 update set col1 = val1 ,...., colN = valN
        update student_log set name = 'libai', age = 22, sex='2'
        where no = '1001';

        -- 3.2 update set(col1,...,colN) = (select) (仅oralce支持)
        update student_log sl set(name,age,sex)=(select name,age,sex from student s where s.no = sl.no);


-- TCL : commit/rollback、ACID
    -- 1. commit 提交
    insert into student_log(no,name,idcard,sex,age) 
    values('2003','libai',null,1,20);

    commit;

    -- 2. rollback 回滚
    insert into student_log(no,name,idcard,sex,age) 
    values('2003','libai',null,1,20);

    rollback;

    -- 3. 事务的四大特性(ACID):原子性(Atomicity)、一致性(Consistency)、隔离性Isolation)、永久性(Durability)
       --事务:一次性完成的一次的DML操作


--我自己认为的事务的4个属性
--1.原子性:事务中包括的操作要么都做,要么都不做(性质)
--2.一致性:事务的转变必须是从一个一致的状态到另一个一致的状态,比如说从2到3不会说有什么2.5的状态
--(状态)
--3.隔离性:一个事务内部的操作及使用的数据,对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰
--4.持久性:一个事务一旦提交,它对数据库中数据的改变就是永久性的

chpt07 DDL(表)

--DDL

--表分类:
  --1. 数据字典表(视图): user_
       select * from user_tables;
  --2. 用户表


--表操作(DDL) & 约束 
----------------- create:创建表 -----------------
--方法:1:create
create table teacher(-- 列级约束
    tno varchar2(10) primary key, -- 主键约束
    tid varchar2(18) unique,      -- 唯一约束
    name varchar2(16) not null,   -- 非空约束
    age number(4) check(age between 20 and 60), -- 检查约束
    sex char(4) default '男' check(sex in('男','女')) -- 检查约束
)

create table teacher(-- 列级约束
    tno varchar2(10) constraint tea_tno_pk primary key, -- 主键约束
    tid varchar2(18) constraint tea_tid_uk unique,      -- 唯一约束
    name varchar2(16) constraint tea_name_nk not null,   -- 非空约束
    age number(4) constraint tea_age_ck check(age between 20 and 60), -- 检查约束
    sex char(4) default '男' check(sex in('男','女')) -- 检查约束
)

create table teacher(-- 表级约束
    tno varchar2(10),       -- 主键约束
    tid varchar2(18),       -- 唯一约束
    name varchar2(16) constraint tea_name_nk not null,   -- 非空约束
    age number(4) , -- 检查约束
    sex char(4) default '男' , -- 检查约束
    constraint tea_tno_pk primary key(tno),
    constraint tea_tid_uk unique(tid),
    constraint tea_age_ck check(age between 20 and 60),
    constraint tea_sex_ck check(sex in('男','女'))
)

insert into teacher(tno,tid,name,age) values('003','1001002','lbai',28);
commit;

select * from teacher;

--方式2:create as select
create table teacher2
as
select*from teacher where 1=0;

----------------- alter:修改表 -----------------
--1. 改名:rename to
rename teacher2 to tea2

--2. 添加列:add
alter table tea2
add(salary number(5))

--3. 修改列:modify
alter table tea2
modify(salary number(8))

--4. 删除列:drop
alter table tea2
drop(salary)

----------------- drop:删除表 -----------------
drop table teacher2;


----------------- truncate:截断表 -----------------
truncate table teacher2;

delete from teacher2;

select* from teacher2;

rollback;

--将表中的数据清空,由于truncate是DDL语句,所以清空不可回滚
--delete & truncate
    --1. delete 只删除符合条件的数据,truncate 则是一次性清空表中所有的数据
    --2. delete 是DML语句,DML语句是事务性的,所以删除的数据可以回滚;而truncate是DDL语句,DDL语句与事务无关。

SELECT (250-37-70-14-14-90-14) FROM dual

chpt08 视图、序列、索引

select * from user_views;

--1. 视图 view
     --a 定义:视图是一张逻辑表(基于表或其他视图),其提供了另外一个视角查看或改变表中的数据,本身并不包含真实的数据
         --b 本质:视图就是一条select语句。
     --c 好处:① 隐藏隐私字段,使数据更安全  ②.简化查询
     --d 语法:
     /*
         create [or replace] view view_name([别名列表])
         as 
            select 查询
         [with check option]
         [with read only]
     */
     --e 分类:
         -- e1. 简单视图: 查询只涉及一张表,不涉及函数或分组,可以做DML操作
         -- e2. 复杂视图:查询涉及多张表或函数或分组,不可以做DML操作,只能做DQL

         create or replace view employee_info
         AS 
                select 
                        e.EMPLOYEE_ID 雇员编号,
                        e.FIRST_NAME || e.LAST_NAME 姓名,
                        e.SALARY    月薪,
                        j.JOB_TITLE 岗位,
                        d.DEPARTMENT_NAME 部门
                from EMPLOYEES e,jobs j,DEPARTMENTS d
                where e.JOB_ID = j.JOB_ID 
                        and e.DEPARTMENT_ID = d.DEPARTMENT_ID

        select 姓名, 岗位, 部门 from employee_info

--2. 序列 sequence (nextval, currval)


--3. 索引 index
    --作用:提高数据的检索效率


    --何时创建索引:
       --1. 表的数据量比较大,则表适合创建索引;反之小表不适合。
       --2. 表频繁做查询,而较少做增删,则适合创建索引;反之增删频繁,查询较少的不合适。
       --3. where条件中出现的字段、多表连接字段



chpt09

表空间 tablespace

-- 表空间 tablespace
    -- 概念:表空间是数据库的逻辑划分,一个表空间只能属于一个数据库。所有的数据库对象都存放在指定的表空间中。但主要存放的是表, 所以称作表空间。
    -- 用户、表、表空间的关系:
         表(商品)放在表空间(仓库)中
         表(商品)属于用户(商家),表空间(仓库)不属于任何用户(商家)

-- 查看已有表空间
select * from DBA_TABLESPACES

/*
    SYSTEM:存储sys/system用户表、存储过程、视图等数据库对象。
    TEMP:临时表空间,用于存储SQL语句处理的表和索引信息。
    USERS:存储数据库用户创建的数据库对象信息。
*/  

-- 查看所有用户
select * from DBA_USERS

用户及权限管理

/*
  DQL: select
  DML: insert、delete、update
  TCL: commit、rollback
  DDL: create、alter、drop、truncate
    DCL: grant、revoke
*/

--1. 用户管理
    --a. 创建 
        create user username
            identified by "密码"
            [default tablespace 表空间]    --不指定时,默认为USERS
            [temporary tablespace 临时表空间|tempgroupname]  --不指定时,默认为 TEMP
            [quota n size|unlimited on 表空间] --指定用户使用表空间的最大值为n,unlimited则表示对表空间使用不限制。
            [profile DEFAULT/profilename]   --表示指定用户的概要文件。
            [account unlock|lock]   --指定用户的锁定状态,lock:锁定状态,unlock:解锁状态。
            [password expire]   --设置当前用户的密码为过期状态,使用户不能登录,要登录必须得重新修改密码。

        create user libai
        identified by "123"
        quota unlimited on users

    --b. 修改
        alter user username
            identified by "密码"
            [default tablespace 表空间]
            [temporary tablespace 临时表空间|tempgroupname]
            [quota n size|unlimited on 表空间]
            [profile DEFAULT/profilename]
            [account unlock|lock]
            [password expire]

        alter user libai account unlock
        alter user libai quota unlimited on users

    --c. 删除 drop user 用户名 cascade (级联删除,即删除用户的同时,删除其拥有的所有对象)
        drop user libai cascade

--2. 权限管理
    --a. 授予系统权限
        。语法:
            GRANT 权限1[,权限2,...]
            TO user | PUBLIC | 角色

        。常用系统权限:
            登录权限:create session
            创建对象:create table | view | sequence | index | procedure  

            grant create session to libai
            grant create table,create view to libai

        --ps: 查看用户拥有的系统权限
            select * from dba_sys_privs where grantee = 'LIBAI'

    --b. 授予对象权限
        。语法:
            GRANT 权限1[,权限2,...]|all -- all:授予全部对象权限
            ON object
            TO user | PUBLIC | 角色
            [with grant option] -- 被授予权限的用户可继续将该权限授予其他用户

        。常用权限:
            insert | delete | update | select 

            grant all on libai.student to libai

            --ps: 查看用户拥有的对象权限
            select * from dba_tab_privs where grantee = 'LIBAI'

    --c. 角色权限
        。概念:权限的集合
            。创建角色:create role 角色名字
                create role temp_role

            。授予系统权限:
                GRANT 权限1[,权限2,...]
                TO 角色

                grant create session,create table,create view to temp_role

            。授予对象权限
                GRANT 权限1[,权限2,...]
                ON object
                TO 角色

                grant all on libai.student to temp_role

            create user dufu identified by 123
            grant temp_role to dufu

    --d. 收回权限:
        。收回系统权限:
            REVOKE 权限1[,权限2,...]
            FROM user | PUBLIC | 角色

            revoke create table from libai -- 将libai创建表的权限收回
            revoke create session from temp_role

        。收回对象权限:
            REVOKE 权限1[,权限2,...]
            ON object
            FROM user | PUBLIC | 角色

            revoke all on libai.student from libai
            revoke all on libai.student from temp_role

chpt10 数据备份及恢复

/*  一、逻辑备份及恢复 */
--数据备份: export
    1>. 表方式
        EXP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log tables=table1, table2, ..., tableN

    2>. 用户方式
        EXP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log

    3>. 全库方式(DBA)
        EXP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log full=y

--数据恢复: import
    1>. 表方式
        IMP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log tables=table1, table2, ..., tableN
            fromuser=otherUsername touser=username 
            commit=y ignore=y

    2>. 用户方式
        IMP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log
            fromuser=otherUsername touser=username 
            commit=y ignore=y

    3>. 全库方式(DBA)
        IMP username/pwd@ip/实例名 file=c:/temp/s.dmp log=c:/temp/s.log
            commit=y ignore=y destroy=y

ps: exp和imp命令直接在cmd使用,不需要登录数据库


/* 二、物理备份及恢复 */
    物理备份:简单的将数据库相关文件进行复制备份。
    分类:
        冷备份:脱机备份
        热备份:联机备份

    恢复:关闭数据库实例,将备份的数据库文件复制回原目录即可。

chpt11 PLSQL语法基础

--PL/SQL 语法基础(基本同java语法)
--PL/SQL
    -- Procedual Language/SQL 是oracle在标准SQL的基础上加入了过程性拓展后形成的一种Oracle数据库特有的、支持应用开发的程序设计语言

--1. pl/sql程序块
  -- 声明:定义变量、常量
  declare
     pi number := 3.14;

  -- 主体:具体的过程
  begin
     dbms_output.put_line(pi);
  end;

--2. 注释
  -- 单行注释:--
  -- 多行注释: /**/

--3. 数据类型
    --3.1 常用数据类型:数字(number)、字符串(varchar)、日期(date)、布尔(boolean)

    --3.2 自定义子类型:subtype<类型名> is <数据类型>
    --3.3 自定义数据类型:type <类型名> is <数据类型> (Oracle允许自定义两种类型:record 记录类型,table 表类型)

    select * from teacher;

    declare
       -- 自定义子类型
       subtype int is number(10);
       subtype string is varchar(32);
       -- 自定record类型
       type tea_record is record(
            tno varchar(32),
            tid varchar(32),
            name teacher.name%TYPE,
            age teacher.age%TYPE,
            sex teacher.sex%TYPE
       );

       age number(4);
       name varchar(32);
       height int := 180;
       tel string := '11000000000';
       tea tea_record;
       tea2 teacher%ROWTYPE;
    begin
       select t.tno,t.tid,t.name,t.age,t.sex into tea from teacher t where tno = '001';
       dbms_output.put_line('height='||height||' tel='||tel);
       dbms_output.put_line(tea.tid);
    end;

--4. 变量 & 常量
    -- 变量:值可变的量
    -- 常量:值不可变的量。常量必须在声明时初始化。
    declare
       age number(4):=23;
       PI constant number:=3.1415926;
    begin
       age := 29;
       dbms_output.put_line(age);
       dbms_output.put_line(PI);
    end;

--5. 运算符
    -- 算数(+ - * /)
    -- 关系(> >= < <= = <> != ^= ~=)
    -- 逻辑(and or not)
    -- 赋值( := )

--6. 表达式
    -- 由变量、常量和运算符结合起来的式子
    3 > 2 and 3 = 1

--7. 语句
    -- 语句以分号(;)结尾,分号是语句的标识

chpt12 PLSQL流程控制、游标

-- 流程控制-选择结构
   -- if...then...[else...]
   -- if...then...elseif...then...
   -- case...when...then...[else...]
   declare
      score number := &val; -- 动态给值
      level char ;
   begin
      if score >= 80 then
        level := 'A';
      else 
        level := 'B';
      end if;
      dbms_output.put_line(level);
   end;

   declare
      score number := 59;
      level char ;
   begin
      if score >= 80 then
        level := 'A';
      elsif score >= 60 then
        level := 'B';
      else
        level := 'C';
      end if;
      dbms_output.put_line(level);
   end;

   declare
      score number := 59;
      level char ;
   begin
      level := 
      case
        when score >= 80 then 'A'
        when score >= 70 then 'B'
        when score >= 60 then 'C'
        else 'D'
      end;
      dbms_output.put_line(level);
   end;

-- 流程控制-循环结构
   -- loop...exit when...
   -- loop...if...then exit...
   -- while...loop
   -- for...in...loop
   -- goto label

   -- loop...exit when...
   declare
      sum1 number := 0;
      s1 number := 1;
   begin
      loop
        sum1 := sum1 + s1;
        s1 := s1 + 1;
        exit when s1 > 100;
      end loop;
      dbms_output.put_line(sum1);
   end;

   -- loop...if...then exit...
   declare
      sum2 number := 0;
      s2 number := 1;
   begin
     loop
        sum2 := sum2 + s2;
        s2 := s2 + 1;
        if s2 > 100 then exit;
        end if;
     end loop;
     dbms_output.put_line(sum2);
   end;

   -- while...loop
   declare
      sum2 number := 0;
      s2 number := 1;
   begin
     while s2 <= 100 loop
        sum2 := sum2 + s2;
        s2 := s2 + 1;
     end loop;
     dbms_output.put_line(sum2);
   end;

   -- for...in...loop
   declare
      sum2 number := 0;
   begin
     for s2 in 1..100 loop
       sum2 := sum2 + s2;
     end loop;
     dbms_output.put_line(sum2);
   end;

-- 游标
   --定义:指向查询结果集的一个指针或指示器
   --操作
     --1 声明游标: CURSOR 游标 IS SELECT...
     --2 打开游标: OPEN 游标,打开游标即执行SELECT语句,游标指向查询结果集的首部
     --3 提取游标:FETCH 游标 INTO 变量[列表]
     --4 关闭游标:CLOSE 游标
   --属性
     -- %FOUND、%NOTFOUND:游标是否找到(是否还有数据)
     -- %ROWCOUNT:游标行数(游标当前指向第几行)
     -- %ISOPEN:游标是否打开
     declare
        -- 说明游标
        cursor stu_cursor is select * from student;   
        stu student%ROWTYPE;  
     begin
        -- 打开游标
        open stu_cursor;
        -- 提取游标
        if stu_cursor%isopen then
          loop
             fetch stu_cursor into stu;
             exit when stu_cursor%NOTFOUND;
             dbms_output.put_line(stu.no||stu.name||stu.idcard||stu.sex||stu.age);
          end loop;
        end if;
        -- 关闭游标
        close stu_cursor;
     end;



chpt13 存储过程、函数、触发器

-- 存储过程:有名称的无返回值的程序块。
    --注意:形参类型不能规定宽度
  create or replace procedure addStu(no varchar,name varchar)
  as 
  begin
    insert into student(no,name) values(no,name);
    commit;
  end;

  call addStu('2','dufu');

  drop procedure addStu;
-- 函数:有返回值的过程
    --注意:形参类型和返回值类型不能规定宽度
   create or replace function getSex(m number)return char
   as
   begin
     if m = 1 then
          return '男';
     elsif m = 0 then
          return '女';
     else 
          return '';
     end if;
   end; 

   select no,name,length(idcard) "ID Length",getSex(sex) 性别 from student;

   drop function getSex;

-- 触发器
    /*
     概念:触发器类似于过程,不同的是,触发器无需主动调用,当满足一定条件时其会自动调用

     触发事件:
        引起触发器执行的事件。如DML语句(insert、update、delete)。

     触发时机:
        1. before:在执行DML之前触发
        2. after:在执行DML之后触发

     条件谓词:
        当触发器中包含了多个触发事件(insert、update、delete),为了分开处理,需用到条件谓词
        1. inserting: 取值 true | false, 当触发事件是insert时。
        2. updating
        3. deleting

      触发子类型:
        1. 行(row)触发:对每一行操作时都要触发,通常执行SQL时都应是行触发。
           --ps: 行触发中,分别用 old和new代表表中的旧值和新值。
        2. 语句(statement)触发:只对这种操作触发一次。
     */
     create or replace trigger dmlStuTrigger
        before insert or delete on student
        for each row
     begin
        if deleting then
          insert into student_log(no,name) 
          values(:old.no,:old.name);
        else
          insert into student_log(no,name) 
          values(:new.no,:new.name);
        end if;
     end;

     drop trigger dmlStuTrigger;

chpt14 分页

分页

发表评论

电子邮件地址不会被公开。 必填项已用*标注