zoukankan      html  css  js  c++  java
  • Oracle基础笔记

    =====================================第一章:oracle数据库基础=============================================
    Orace特点: 
             1.跨操作系统,跨硬件平台的数据操作能力
         2.支持多用户,大事务量的处理
             3.在保持数据安全性和完整性方面的性能优越
             4.支持分布式数据处理,具有可移植性
     
     
    Sqlserver特点:
             1.只能在windows上运行
     
    Oracle和Sqlserver两者的共同点:
     
                     1.都是关系型数据库
     
    表空间:
           1. 一个表空间可以由多个数据文件组成,但一个数据文件只能属于一个表空间
     
     
    数据库文件扩展名为:【.dbf】
    控制文件的扩展名为:【.ctl】
    日志文件的扩展名为:【.log】
     
    -------------------------------------------------------------
    数据类型:
            char-------1-2000字节,默认是一个字节
     
        varchar2---1-4000字节,可变长度字符串
     
        nchar------国家字符集,用来存储Unicode字符集类型
     
            Nvarchar---可变长的国际字符串
     
            number(p,s)-----【p】表示数字的有效位数[1-38位数之间],从左边第一个不为0的数算起,小数点和负号不计入有效位数
                【s】表示数字的小数位数
     
            Date------------使用7字节固定长度,返回了世纪 【SysDate】函数的功能是返回当前的日期和时间
     
            TimeStamp-------用来存储日期的,年,月,日,小时,分钟,秒,精确到小数点后6位
                            【SysTimeStamp】函数返回的是当前的日期和时区
     
            Lob------------大对象数据类型,可以存储多达4GB的非结构信息
               分为:
            Clob:存储大量的字符数据,如新闻,内容介绍
                    Blob:存储较大的二进制对象,如图片,视频,声音等
             Bfile:支持的文件最大位4GB,存储的是一个Bfile定位器
                    BClob:存储大的Nchar字符数据,最大4GB与CLob类似
     
    ------------------------伪列--------------------------------------
    rowID:
         1.返回该行地址
     
         2.能以最快的方式访问表中的一行
     
         3.能显示表的行是如何存储的
     
         4.可以作为表中行的唯一标示
     
     语法:    select rowID,eName 
           from scott.emp 
        where eName='SMITH'
     
     
    rowNum:
          1.返回一个数值代表行的次序
          2.总是从1开始的伪列
          3.大于某列查不出数据
          4.只能等于1
     
       语法:select emp.* rownum
        from scott.emp
        where rownum<11
    ---------------------------------数据定义语音DDL-------------------------------
    -------创建表create table-----
    语法:
        create table Stuinfi
        (
           stuName varchar2(20) not null,
           stuAge number(3,0) not null,
          stuID number(18,0) ,
          stuSeat number(2,0) 
        )
     
     
    -----删除表的记录而不删除表的结构:truncate table-----
    语法:
        truncate table student
     
     
    ------------------------------数据操纵语言DML-----------------------------------
    忽略重复行:[distinct]
     
              语法:
            select distinct name,age
            from student
     
     
    创建新表:
         create table student_1
           as
         select*from student
     
     
    user_all_tables:为系统提供的数据视图
     
    -------------------------------------
    查看用户所以数据量大于100的表的信息 
        select table_name
        from user_all_tables a
        where a.num_rows>100
     
    ------------------------------事务控制语言TCL-------------------------------------
    commit:提交事务
    rollback:回滚事务
    savepoint:在事务中创建存储点
     
    -----------------------------------集合操作符----------------------------
    注意事项:
        1.通过集合操作符链接的各个查询具有相同的列数,而且对应列的数据类型必须兼容
         2.这种查询不应含有long类型的列,列标题来自第一个select语句
     
    Union【并集】:返回两个查询所有不重复的行
     
    UnionAll【并集ALL】:返回两个查询的所有行
     
    intersect【交集】:返回两个查询都有的行
     
    minus【减集】:返回两个查询中第一个查询里面所有的列
     
    语法:
        select stuNo from student
        union
        select stuNo from subject
     
     
    --------------------------------链接操作符【||】-----------------------
     
    ||操作符:
        将两个或多个字符串合并成一个字符串,或将一个字符和一个数值合并在一起
     
    示例:
        select jon||'_'||ename from student
     
    ------------------------------函数--------------------------------------
    函数的几大类:
        1.单行函数
            1.字符函数
            2.日期函数
            3.数字函数
            4.转换函数
        2.聚合函数
     
        3.分析函数
     
    转换函数:
        1.TO_char   转换成字符串类型【dual--伪表】
                  示例:
             select To_char(sysdate,' YYYY"年"fmMM"月"fmDD"日" HH24:MI:SS  ') from dual
     
     
     
              结果:2013年7月10日 21:21:22
                     不使用fm填充 月份会自动补0
     
        2.TO_Date   转换成日期类型
              示例:
             select To_date('2013-03-13','yyyy-mm-dd') from student
                  结果:
             2013-03-13
     
        3.TO_Number 转换成数值类型
     
    其他函数:【转换空值】
        nvl(stu-1,stu-2)-----------如果stu-1的值为null,则返回stu_2,否则返回stu-1的值
     
        nvl2(stu-1,stu-2,stu-3)----如果stu-1的值为null,则返回stu-2的值,否则返回stu-3的值
     
        decode(value,if-1,then-1,if-2,then-2,...,else)
                   如果value的值为if-1,则返回then-1的值,以此类推,否则返回else的值
     
    注意:
         任意值与null值进行“+”运算,结果为null
     
     
     
    分析函数:
          Row_number:返回一个唯一的值,有相同数据时,[按照记录集中的记录的顺序依次递增]
        dense_rank:返回一个唯一的值,有相同数据时,[所以相同数据的排名都是一样的]
              rank:返回一个唯一的值,有相同数据时,[所以相同数据的排名都是一样的,同时会在最后一条相同记录和下一条不同记录的排名之间空出排名]
     
    语法示例:
        select ename,
                   deptno,
                   sal,
                   row_number() over(Partition by deptno order by sal desc) "row_rownum",
                  dense_rank() over(Partition by deptno order by sal desc) "dense_rank",
                   rank()          over(Partition by deptno order by sal desc) "rank"       
        from Employee
     
    ===============================================第二章=======================================================
     
     
     
    ***************************************************表空间*******************************************
    类别:
        1.永久性表空间------>默认安装,用来存储表,视图,过程,索引等
        2.临时性表空间------>保持系统短期活动的数据,如排序数据等
        3.撤销性表空间------>用来帮助回退未提交的事务数据
     
    --------创建表空间语法:【多个用逗号隔开】----------
     
    create tablespace sample
    datafile 'E:OracleDBTableSpacesample.dbf'
    size 10M
    Autoextend on;
     
    ---------修改改数据大小的语法:--------------------
     
    alter database 
    datafile 'E:OracleDBTableSpacesample.dbf'
    resize 10M
     
    ----------向表空间添加数据文件---------------
     
    alter tablespace sample
    add datafile 'E:OracleDBTableSpacesample01.dbf'
    size 5M
    Autoextend on
     
    ----------添加表空间只读--------------------------
     
    alter tablespace sample readonly;        
     
    ----------查看表空间信息:-----------------
     
    select  file_name,
        tablespace_name,
        bytes,
        autoextensible
    from dba_data_files
    where tablespace_name='表空间名称';
     
    ----------删除表空间信息------------------
     
    ----没数据的时候删除的方法
    1:drop tablespace sample
     
    ----包含数据时删除的方法【注意备份数据】
    2:drop tablespace sample including contents
     
     
    --------------注意:------------------------------     
        2.出现错误号01029,使用sysdba登录运行一下脚本
        -----步骤1
        alter database open;
        -----步骤2
        alter database datafile 'E:javaOraclech02sample.DBF' offline drop;
     
     
    *******************************************自定义用户管理***********************************************
     
    -----------创建一个新的自定义用户----------------------
     
    create user accp                --用户名称
    identified by accp              --密码
    default tablespace sample       --物理表空间
    temporary tablespace temp;      --临时表空间
     
     
    -----------修改用户信息--------------------------
    alter user accp
    identified by accp_Pwd
     
    ----------删除自定义用户--------------------------------
    drop user accp cascade
     
    ********************************************数据库权限管理*********************************************
     
    常见的系统权限:
                 1.create session------------连接到数据库
                2.create table--------------创建表
            3.create view---------------创建视图
            4.create sequence-----------创建序列
    对象权限:
        1.connect-------连接数据库
        2.resource-----可以创建表,数据库,存储过程等
        3.dba----------数据库管理员角色,最高权限    
     
     
    -----------------------------授权:分配系统权限--------------------------------------------------
    ---授予用户创建表,视图,表空间,序列的权限到accp用户
    grant create session,
          create table,
          Create view,
          create user,
          create Sequence to accp;
    --授予单个权限到accp用户
    grant create Tablespace to accp;
    grant  drop Tablespace to accp;
    grant drop user accp;
     
    ---将链接权限授予所有用户
    grant create session to public
     
    --使被授予者进一步将权限或角色授予其他用户或角色
     
    grant create session, 
          create table,
          create view,
          create Sequence to accp with admin option --支持管理员选项
     
    --撤销权限-来自accp用户
    revoke create user from accp;
     
     
    ----------------------------------授权:对象权限---------------------------------------------
     
    --连接数据库的角色,多个角色有","号隔开
    grant connect to accp;
    --一般角色
    grant resource to accp;
    ---最高角色
    grant dba to accp;
     
    ------撤销权限
    revoke connect from accp;
     
     
    --授予用户accp修改System模式下emp表的权限
    grant update on scott.emp to accp;
     
    ---授予用户accp对于emp表的增删改查权限
    grant all on scott.emp to accp with grant option;
    ---查看权限
    select * from DBA_SYS_PRIVS where grantee ='accp';
     
    **********************************************序列********************************************************
     
    -------在accp用户中插入student表
    create table accp.student
    (
      stuNo number not null primary key,
      stuName varchar(20) not null,
      stuAge number(3) not null
    )
    ----创建序列,从序号10开始,每次增加1,最大位2000,不循环,缓存为30
    create sequence accp.seq_stuNo
    Start with 10
    increment by 1
    maxvalue 2000
    Nocycle
    cache 30;
     
    ------删除序列
    drop sequence accp.sql_stuNo
     
    -----更改序列:---不能修改start with 参数
    alter sequence accp.Seq_Stuno
    Increment by 2
     
     
    -----插入数据[nextval]
    insert into accp.student
     values(seq_stuNo.nextval,'小白',10)
     
    ----查看序列当前值
    select accp.Seq_Stuno.Currval from dual
     
    ----查看所有序列
    select sequence_name from dba_sequences
     
    select sequence_name from ALL_SEQUENCES;
     
    select sequence_name from USER_SEQUENCES;
     
    select sequence_name from DBA_SEQUENCES;
     
    ----插入数据
    insert into accp.Student values(accp.Seq_Stuno.nextval,'小白',10);
    insert into accp.Student values(accp.Seq_Stuno.nextval,'小白',10);
    insert into accp.Student values(accp.Seq_Stuno.nextval,'小白',10);
    insert into accp.Student values(accp.Seq_Stuno.nextval,'小白',10);
    commit;
     
    *******************************************同义词********************************************************
    同义词的用途:
               1.简化SQL语句
            2.隐藏对象的名称和所有者
                3.为分布式数据库的远程对象提供了位置透明性
            4.提供对对象的公共访问
    分类:
        1.私有同义词----只能被当前模式的用户访问,创建时必须拥有create synonym系统权限
        2.公有同义词----能被所有数据库用户访问,创建时必须拥有create public synonym系统权限
     
     
     
    --授予accp创建同义词的权限
    grant create synonym to accp;
    grant create public synonym to accp;
    grant create any synonym to accp;
    ------创建私有同义词
    create or replace synonym stu
    for accp.Student
     
    ----创建公有同义词
    create or replace public synonym stu
    for student
    select*from stu
     
    -------删除同义词
    drop synonym stu
    drop public synonym stu
    ****************************************************视图*************************************************
    --获得create view权限
     
    create or replace view v_myorders
    as
    select * 
      from orders 
     where sales_rep_id=(select empno
                           from employee 
                          where ename=(select user from dual));
     
    select * from v_myorders;
     
    --当前用户a_hr
    create or replace view v_employee
    as
    select empno,ename,e.deptno,dname 
      from employee e inner join dept d 
        on e.deptno=d.deptno;
     
    ***************************************************索引*************************************************
     
    -----在sample表空间的student表里创建B树索引
    create unique index idx_unique_stuNo on Student(stuName)
    tablespace sample;
     
    --在sample表空间的student表里创建位图索引
    create bitmap index idx_bitmap_stuName on student(Stuage)
    tablespace sample;
     
    ------------------主键列创建反向键索引
    create unique index idx_empno on employee(empno) reverse; --先创建反向键索引
    --主键引用反向键索引
    alter table employee add constraint pk_empno primary key(empno) using index idx_empno;
     
     
    ----------删除索引
    drop index idx_unique_stuNo
     
    ---------重建索引:将反向键索引重建成B数索引
    alter index idx_uinque_stuNo Rebuild noreverse
     
    -------移动索引到那个表空间里面
    alter index idx_unique_stuNo rebuild tablespace sample
     
    *****************************************分区表**********************************************************
    分区表的优点:
        1.改善表的查询性能
        2.更容易管理
        3.便于备份和恢复
        4.提高了数据的安全性
     
    分区表的几大类:
        1.范围分区
        2.列表分区
        3.散列分区
        4.复合分区
        5.间隔分区  --oracle 11g的新增特性
        6.虚拟分区  --oracle 11g的新增特性
     
    注意:分区删除,里面的数据也会随之删除
     
    ------------创建分区表(按范围分区)
    create table sales_range1
    (sales_id   number not null,
     product_id   varchar2(5),
     sales_date   date,
     sales_cost   number(10),
     areacode    varchar2(5)
    )
    partition by range(sales_date)
    (partition part1 values less than (to_date('2011/01/01','yyyy/mm/dd')),
     partition part2 values less than (to_date('2012/01/01','yyyy/mm/dd')),  
     partition part3 values less than (to_date('2013/01/01','yyyy/mm/dd')),  
     partition part4 values less than (to_date('2014/01/01','yyyy/mm/dd'))
    )tablespace sample;
     
    --查询分区情况
    select table_name,partition_name 
      from user_tab_partitions 
     where table_name=upper('sales_range1');
     
    --插入数据
    insert into sales_range1 values (1000,'p1',to_date('2011-01-01','yyyy-mm-dd'),1000,'a1');
     
    --查询数据
    select * from sales_range1 partition (part3);
     
     
    --------------------以有表创建分区
    create TABLE sales_range2
    partition by range(sales_date)
    (partition part1 values less than (to_date('2011/01/01','yyyy/mm/dd')),
     partition part2 values less than (to_date('2012/01/01','yyyy/mm/dd')),  
     partition part3 values less than (to_date('2013/01/01','yyyy/mm/dd')),  
     partition part4 values less than (to_date('2014/01/01','yyyy/mm/dd'))
     Partition part5 values less than(maxvalue)
    )tablespace sample
    as select * from sales_range1;
     
    select*from sales_range2 partition(part2)
     
    -----------------------间隔分区------------------------
    create table sales_interval1
    (sales_id   number not null,
     product_id   varchar2(5),
     sales_date   date,
     sales_cost   number(10),
     areacode    varchar2(5)
    )
    partition by range(sales_date)
    interval(numtoyminterval(1,'year'))
    (partition part1 values less than (to_date('2011/01/01','yyyy/mm/dd')));
     
    --查询分区情况
    select table_name,partition_name,tablespace_name 
    from user_tab_partitions 
    where table_name=upper('sales_interval1');
     
    insert into sales_interval1 values (1000,'p1',sysdate,2000,'a2');
     
    select * from sales_interval1 partition (sys_p142);
     
    --现有表创建新表
    create table sales_interval2
    partition by range(sales_date)
    interval(numtoyminterval(1,'year'))
    (partition part1 values less than (to_date('2011/01/01','yyyy/mm/dd')))
    as select * from sales;
     
    /*
    ===========================================================
    |          分区表的管理
    ============================================================
    */
     
    --查询分区情况
    select table_name,partition_name 
      from user_tab_partitions 
     where table_name=upper('sales_range1');
     
    select * from sales_range1 partition (part1);--11前
    select * from sales_range1 partition (part2);--12前
    select * from sales_range1 partition (part3);--13前
    select * from sales_range1 partition (part4);--14前
     
    --插入数据
    insert into sales_range1 values (2000,'p1',to_date('2014-01-01','yyyy-mm-dd'),1000,'a1');
     
    --添加分区
    alter table sales_range1 add partition part5 values less than (to_date('2015-01-01','yyyy-mm-dd'));
    alter table sales_range1 add partition part6  values less than (maxvalue);
     
    select * from sales_range1 partition (part5);--15前
     
    --删除分区
    alter table sales_range1 drop partition part5  
     
    select * from sales_range1 where sales_id=2000;
     
    --移动分区
    alter table sales_range1 move partition part1 tablespace tp_sales_bak;
    --表空间只读后测试插入数据,失败。
    insert into sales_range1 values (3000,'p1',to_date('2009-01-01','yyyy-mm-dd'),1000,'a1');
     
     
    --表空间
    create tablespace tp_sales_bak 
           datafile 'd:data p_sales_bak.dbf' size 100m;      
    alter user a_oe quota unlimited on tp_sales_bak;
     
    --移动完表空间后将表空间设置为只读
    alter tablespace tp_sales_bak read only;
     
    alter tablespace tp_sales_bak read write;
    ==================================================第3章:PL/SQL编程==========================================
     
    PL/SQL:
        1.结合了oracle过程语言和结构化查询语言的一种扩展语言
        2.能把一组SQL语句放到一个模块中,使其更具模块化程序特点
        3.可采用过程语言控制程序的结构
        4.对错误进行自动处理
        5.具有更好的可移植性
        6.减少了网络的交互,有助于提高程序的性能
     
    PL/SQL:【分成三部分】
        1.声明部门--declare
        2.执行部门--begin end
        3.异常处理--exception
    属性类型:
        %type-------不必知道数据类型
        %rowtype----不必知道列的个数和数据类型
     
    赋值方法【两种方式】:
        1.v_name:='aa';
        2.select ename into v_name from student where stuno=1;    
     
    异常:
        1.预定义异常
        2.用户自定义异常
     
     
     
    --进行预异常处理
    declare
       v_ename employee.ename%type;
    begin
       select ename into v_ename 
       from employee 
       where empno=1234;
       dbms_output.put_line('雇员名:'||v_ename);
    exception
       when no_data_found then
          dbms_output.put_line('雇员号不正确');   
       when too_many_rows then
          dbms_output.put_line('查询只能返回单行');
       when others then
          dbms_output.put_line('错误号:'||sqlcode||'错误描述:'||sqlerrm);
    end;
     
     
    ----用户自定义异常
    declare
         v_comm employee.comm%type;
        e_comm_is_null exception; --定义异常类型变量
    begin
        select comm into v_comm from employee where empno=7788;
        if v_comm is null then
           raise e_comm_is_null;
        end if;
    exception
        when no_data_found then
           dbms_output.put_line('雇员不存在!错误为:'||sqlcode||sqlerrm);
        when e_comm_is_null then
             dbms_output.put_line('该雇员无补助');
        when others then
             dbms_output.put_line('出现其他异常');
    end;
     
     
     
    --需求:修改编号为7788的雇员所属的部门编号为99。
    --前提是要在employee和dept表建立主外键约束
    alter table employee 
       add  constraint pk_empno primary key(empno);
    alter table dept 
       add  constraint pk_deptno primary key(deptno);
    alter table employee 
       add  constraint fk_deptno foreign key(deptno) references dept(deptno);
     
    declare
       e_integrity exception;
       pragma exception_init(e_integrity,-2291);  --  -2291为oracle定义的错误号,违背了主外键约束
    begin
     update employee set deptno=99 where empno=7788;
    exception
       when e_integrity then
          dbms_output.put_line('该部门不存在');
    end;
     
    select * from employee;
     
     
     
     
     
     
     
     
     
    不忘初心,方得始终
  • 相关阅读:
    PHPStorm--美化
    Laravel5.1 模型--关联关系(复杂)
    HTML5 getUserMedia/AudioContext 打造音谱图形化
    如何在终端实时展现当前运行的git分支
    关于ionic的跨域问题
    ionic插件安装与卸载
    虚拟机调试ionic项目
    ionic双击退出键退出APP
    npm install 镜像
    对Date的扩展,将 Date 转化为指定格式的String
  • 原文地址:https://www.cnblogs.com/Allen974103107/p/5537688.html
Copyright © 2011-2022 走看看