【筆記】Oracle SQL語句 | 進階篇


之前整理了Oracle SQL基本語句,主要針對Oracle的初學者:

【筆記】Oracle SQL語句 | 基礎篇

隨着學習的深入和工作需求的提高,需要從會用會寫進階到會管理會維護,因此整理了SQL語句進階篇。這部分的學習一個是要跟Oracle體系的知識點結合以來一起學,明白語句背后的原理,另一個是要在具體的管理維護中多實踐多操作,才能熟練。

  

----------1. 用戶管理/權限-------------
------1.1 用戶管理
---創建
create user mr 
identified by mrsoft  --externally/globally as 'CN=user'
default tablespace users
temporary tablespace temp
quota 10m on tbsp_1

---修改
alter user east quota 20m on tbsp_1;
alter user east identified by 123456;  --密碼
alter user SH account unlock;  --解鎖

---刪除
drop user df cascade;

------1.2 用戶權限
---授權
--系統
grant connect,resource to east;
grant create session,create table to dongfang with admin option; --再授權
--對象
grant select,insert,delete on scott.emp to xifang;

---回收
revoke resource to east;
revoke delete on scott.emp from xifang;

---查詢
--DBA_USERS  用戶基本信息表
--DBA_SYS_PRIVS  系統權限
--DBA_TAB_PRIVS  對象權限
--USER_SYS_PRIVS  用戶系統權限
--ROLE_SYS_PRIVS  用戶角色
--ALL_TABLES  可以查詢的基本信息
--USER_TAB_PRIVS  用戶將權限授予哪些用戶
--ALL_TAB_PRIVS  哪些用戶給自己授權
select * from USER_SYS_PRIVS;

------1.3 用戶角色
---預定義
--connect/resource/dba/exp_full_database/imp_full_database

---創建
create role designer identified by 123456;
grant create view,create table to designer;

---授予
grant designer to dongfang;

---管理
select * from role_sys_privs where role = 'DESIGNER';
alter role designer not identified;
alter role designer identified by mrsoft;
set role designer;  --生效  indentified by mrsoft;

---刪除
drop role designer;

------1.4 資源配置PROFILE
---管理密碼
create profile lock_account limit
failed_login_attempts 5
password_lock_time 7;  
--password_life_time/password_grace_time
--password_reuse_time/password_reuse_max
--password_verify_function

alter user dongfang profile lock_account;

---管理資源
alter system set resource_limit = true;

alter profile password_lift_time limit
cpu_per_session 20000
sessions_per_user 10
cpu_per_call 500
password_life_time 180
failed_login_attempts 10;

---刪除
drop profile password_life_time cascade;

---查詢
select profile from dba_users where username = 'SCOTT';
select resource_name,resource_type,limit from dba_profiles 
where profile = 'DEFAULT';


----------2. 數據對象-------------
------2.1 數據表
---創建
create table students(
  stuno number(10) not null,  --非空約束
  stuname varchar2(8),
  id varchar2(18) constraint ID_UK unique,  --唯一性約束
  sex char(2),
  age int constraint AGE_CK check(age > 0 and age < 120) disable,  --禁用
  departno varchar2(2) not null,
  classno varchar2(4) not null,
  regdate date default sysdate,
  ---blob/clob/bfile
  constraint STU_PK primary key(stuno)  ---主鍵約束
)tablespace tbsp_1  --表空間
storage(initial 256k)  --存儲參數next/minextents(AUTOALLOCATE)
pctfree 20  --數據塊最小空閑空間比例,達到后標記不可用
pctused 40  --數據庫是否可用界限
initrans 10  --允許並發事務數目
nologging;  --DDL操作不產生日志

---維護
--字段
alter table students add(province varchar2(10));
alter table students drop column province;
alter table students drop (sex,age);
alter table students modify departno varchar2(4);
--重命名
alter table students rename to students_bak;
--表空間
alter table students move tablespace tbsp_2;
--存儲參數
alter table students pctfree 25 pctused 45;
---刪除
drop table students cascade constraints;  --同時刪除視圖,約束或觸發器等
flashback table students to before drop;  --閃回
--狀態
alter table students read only;  --read write
--約束
--
alter table students modify stuno not null;  ---null
--
alter table students add constraint STUD_PK(stuno);
alter table students drop constraint STUD_PK;
--
alter table students add constraint IDs_UK unique(id);
alter table students drop constraint IDs_UK;
--
alter table students add constraint DEPART_FK foreign key(department_id)
      reference departments(department_id);  --外鍵約束
alter table students drop constraint depart_FK;
--
alter table students enable validate constraint depart_FK;  --novalidate
alter table students disable constraint depart_FK;


------2.2 索引
---創建
create index emp_deptno_index ---bitmap index
on emp(deptno)  --emp(lower(job))
pctfree 25  --reverse
tablespace users;

---合並
alter index emp_deptno_index coalesce deallocate unused;

---重建
alter index emp_deptno_index rebuild;

---刪除
drop index emp_job_fun;

---查詢
select table_name,index_name,index_type from dba_indexes 
where owner = 'HR';  --表索引 sys
select column_name,column_length from user_ind_columns 
where index_name = 'EMP_DEPTNO_INDEX';  --索引列 scott
select tablespace_name,segment_type,bytes from user_segments
where segment_name = 'EMP_DEPTNO_INDEX';  --索引段 scott
select column_expression from user_ind_expressions
where index_name = 'EMP_JOB_FUN';  --函數索引

------2.3 視圖
---創建
create or replace view emp_view as
  select d.dname,d.loc,e.empno,e.ename
  from emp e, dept d
  where e.deptno = d.deptno and d.deptno = 20
with read only;

---查看
select * from emp_view;
desc emp_view;

---重編譯
alter view emp_view compile;

---刪除
drop view emp_view;

------2.4 同義詞
---創建
create public synonym public_dept for scott.dept;
create synonym private_dept for dept;

---刪除
drop public synonym public_dept;
drop synonym private_dept;

------2.5 序列
---創建
alter sequence empno_seq
start with 100
maxvalue 100000  --minvalue/nominvalue/nomaxvalue
increment by 200
cache 100
cycle  --nocycle
order  --noorder

---管理
alter sequence empno_seq
maxvalue 500000
increment by 200;

---刪除
drop sequence empno_seq;


----------3. 表/索引分區-------------
------3.1 表分區
---創建
--范圍
create table ware_retail_part
(
  id integer primary key,
  retail_date date,
  ware_name varchar2(50)
)
partition by range(retail_date)
(
  partition par_01 values less than(to_date('2011-04-01','yyyy-mm-dd')) tablespace TBSP_1,
  partition par_02 values less than(to_date('2011-07-01','yyyy-mm-dd')) tablespace TBSP_1,
  partition par_03 values less than(to_date('2011-10-01','yyyy-mm-dd')) tablespace TBSP_2,
  partition par_04 values less than(to_date('2012-01-01','yyyy-mm-dd')) tablespace TBSP_2 
);

--散列
create table goods
(
  id number,
  goodname varchar2(50)
)
storage(initial 2048k)
partition by hash(id)
(
 partition par1 tablespace tbsp_1,
 partition par2 tablespace tbsp_2
);

--列表
create table clients
(
  id integer primary key,
  name varchar2(50),
  province varchar2(20)
)
partition by list(province)
(
  partition shandong values('山東省'),
  partition guangdong values('廣東省'),
  partition yunnan values('雲南省')
);

--組合
create table person2
(
  id number primary key,
  name varchar2(20),
  sex varchar2(2)
)
partition by range(id)  --范圍分區
subpartition by hash(name)  --hash子分區
subpartitions 2 store in(tbsp_1,tbsp_2)  --存儲在兩個不同的命名空間中
(
  partition par1 values less than(5000),
  partition par2 values less than(10000),
  partition par3 values less than(maxvalue)
);

--Interval
create table saleRecord
(
 id number primary key,
 goodsname varchar2(50),
 saledate date,
 quantity number
)
partition by range(saledate)
interval (numtoyminterval(1,'year'))
(
  partition par_fist values less than (to_date('2012-01-01','yyyy-mm-dd'))
);

--應用
insert into ware_retail_part values(1,to_date('2011-01-20','yyyy-mm-dd'),'PC');
insert into ware_retail_part values(2,to_date('2011-04-15','yyyy-mm-dd'),'TV');

select * from ware_retail_part partition(par_02);

---管理
--添加
alter table clients
add partition hebei values('河北省')
storage(initial 10K next 20k) tablespace tbsp_1
nologging;

--合並
alter table person coalesce partition;
alter table person2 modify partition par3 coalesce subpartition;

--刪除
--disable constraint/drop/enable constraint
delete from ware_retail_part where retail_date>=to_date('2011-10-01','yyyy-mm-dd');  --數據
alter table ware_retail_part drop partition par_04;  --表分區
alter index ware_index rebuild;  --重建索引

--並入
alter table sales merge partitions part_sea3,part_sea4 into partition part_sea4;
alter table sales modify partition part_sea4 rebuild unusable local indexes;  --重建局部索引

------3.2 索引分區
---創建
--本地
--create tablespace ts_1/ts_2/ts_3;
--create table studentgrade partition by range(grade);
create index grade_index on studentgrade(grade)
local
(
  partition p1 tablespace ts_1,
  partition p2 tablespace ts_2,
  partition p3 tablespace ts_3
);  --dba_ind_partitions
--全局
create index index_SalePrice on Books(SalePrice)
global partition by range(SalePrice)
(
  partition p1 values less than (30),
  partition p2 values less than (50),
  partition p3 values less than (maxvalue)
);

---管理
--刪除
alter index index_saleprice drop partition p2;
alter index index_saleprice drop partition p1;
alter index index_saleprice rebulid partition p3;
--重命名
alter index index_saleprice rename partition p3 to p_new;

----------4. 數據庫管理-------------
------4.1 數據文件/表空間
---查看
select tablespace_name,file_name,bytes from dba_data_files order by tablespace_name;

---默認
select segment_type,segment_name,owner from dba_segments where tablespace_name='USERS';
--SYSTEM/SYSAUT/UNDOTBS1/USERS/EXAMPLE/TEMP

---創建
--本地化管理方式
create tablespace tbs_test_1 datafile 'D:\OracleFiles\OracleData\datafile1.dbf'
size 10m
extent management local uniform size 256K;  --autoallocate
--段空間管理方式
create tablespace tbs_test_3 datafile 'D:\OracleFiles\OracleData\datafile3.dbf'
size 20m
extent management local autoallocate
segment space management manual;  --auto
--非標准塊
alter system set db_16k_cache_size = 16M scope=both;
create tablespace tbs_test_5 datafile 'D:\OracleFiles\OracleData\datafile5.dbf'
size 64m reuse
autoextend on next 4m maxsize unlimited
blocksize 16k
extent management local autoallocate
segment space management auto;
--大文件
create bigfile tablespace tbs_test_big datafile 'D:\OracleFiles\OracleData\datafilebig.dbf'
size 2g;

---維護
--默認
alter database default temporary tablespace temp_1;
alter database default tablespace tbs_example;
--狀態
alter tablespace tbs_test_3 read only;  --read write
--重命名
alter tablespace tbs_test_3 rename to tbs_test_3_new;
--刪除
drop tablespace tbs_test_1 including contents cascade constraint;
--文件
alter tablespace users add datafile 'e:\app\Administrator\oradata\orcl\users02.dbf'
size 10m autoextend on next 5m maxsize unlimited;  --添加
alter tablespace users drop datafile 'e:\app\Administrator\oradata\orcl\users02.dbf';  --刪除
alter database datafile 'D:\OracleFiles\OracleData\datafile2.dbf'
autoextend on next 10m maxsize unlimited;  --自動擴展

---撤銷表空間
--創建
create undo tablespace undo_tbs_1
datafile 'D:\OracleFiles\OracleData\undotbs1.dbf'
size100M;
--修改
alter tablespace undo_tbs_1 
add datafile 'D:\OracleFiles\OracleData\undotbs_add.dbf' 
size 2g;
--切換
alter system set undo_tablespace=undo_tbs_1;
--刪除
alter system set undo_tablespace=undotbs1;
drop tablespace undo_tbs_1;
--查詢
show parameter undo_tablespace;  --undo_management/undo_retention
select tablespace_name from dba_tablespaces where contents = 'UNDO';
select to_char(begin_time,'hh24:mi:ss'), to_char(end_time,'hh24:mi:ss'), undoblks
from v$undostat order by begin_time;  --表空間統計信息
select rn.name,rs.xacts,rs.writes,rs.extents
from v$rollname rn,v$rollstat rs where rn.usn = rs.usn;  --段統計信息
select name,status from v$transaction;  --活動事務
select segment_name, extent_id,bytes,status from dba_undo_extents
where segment_name='_SYSSMU3_991555123$';  --UNDO區信息

---臨時表空間
--創建
create temporary tablespace temp_01 tempfile 'D:\OracleFiles\tempfiles\temp_01.tpf' size 300m;
alter database default temporary tablespace temp_01;
--重命名/刪除同上
--查詢
select file_name,bytes,tablespace_name from dba_temp_files;
---臨時表空間組
create temporary tablespace tp1 tempfile 'D:\OracleFiles\tempfiles\tp1.tpf' 
size 10m tablespace group group1;
create temporary tablespace tp2 tempfile 'D:\OracleFiles\tempfiles\tp2.tpf' 
size 20m tablespace group group1;  --創建
create temporary tablespace tp3 tempfile 'D:\OracleFiles\tempfiles\tp3.tpf' 
size 10m tablespace group group3;
alter tablespace tp1 tablespace group group3;  --轉移
alter user hr temporary tablespace group3;  --分配
alter database orcl default temporary tablespace group3;  --默認
drop tablespace tp1 including contents and datafiles;

------4.2 控制文件
---多路復用
alter system set control_file=
  'D:\PROGRAM\ORACLE\ORADATA\ORCL\CONTROL01.CTL',
  'D:\PROGRAM\ORACLE\FLASH_RECOVERY_AREA\ORCL\CONTROL02.CTL',
  'D:\OracleFiles\ControlFiles\CONTROL03.CTL'
scope=spfile;  --參數設置后復制文件
select name from v$controlfile;  --查看

---創建
select member from v$logfile;  --查看日志文件
select name from v$datafile;  --查看數據文件
select name from v$controlfile;  --查看控制文件
shutdown immediate;  --關閉數據庫,然后備份文件
startup nomount;  --啟動數據庫實例,不加載數據庫
create controlfile reused --創建新控制文件
database "orcl"
logfile
group 1 'D:\PROGRAM\ORACLE\ORADATA\ORCL\REDO01.LOG',
group 2 'D:\PROGRAM\ORACLE\ORADATA\ORCL\REDO02.LOG',
group 3 'D:\PROGRAM\ORACLE\ORADATA\ORCL\REDO03.LOG'
datafile
'D:\PROGRAM\ORACLE\ORADATA\ORCL\SYSTEM01.DBF',
'D:\PROGRAM\ORACLE\ORADATA\ORCL\SYSAUX01.DBF',
'D:\PROGRAM\ORACLE\ORADATA\ORCL\UNDOTBS01.DBF',
'D:\PROGRAM\ORACLE\ORADATA\ORCL\USERS01.DBF',
'D:\PROGRAM\ORACLE\ORADATA\ORCL\EXAMPLE01.DBF',
'D:\PROGRAM\ORACLE\PRODUCT\11.2.0\DBHOME_1\ORADATA\KPLAYER\KPLAYER.DBF'
maxlogfiles 50
maxlogmembers 3
maxinstances 6
maxdatafiles 200
noresetlogs
noarchivelog;
alter system set control_files=  --編輯參數
  'E:\PROG\ADMIN\ORADATA\ORCL\CONTROL01.CTL',
  'E:\PROG\ADMIN\FLASH_RECOVERY_AREA\ORCL\CONTROL02.CTL'
scope=spfile;
alter database open;  --打開數據庫 [resetlogs]

---備份
alter database backup controlfile 
to 'D:\OracleFiles\ControlFiles\ctf.bak';  --二進制文件
alter database backup controlfile to trace;  --腳本文件
show parameter user_dump_dest;

---恢復
--關閉->復制覆蓋->重啟
--關閉->編輯CONTROL_FILES->重啟

---刪除
--關閉->編輯CONTROL_FILES->重啟

---查詢
--v$controlfile  所有控制文件名稱和狀態
--v$controlfile_record_section  控制文件各記錄文檔段信息
--v$parameter  系統所有初始化參數

------4.3 重做日志文件
---增加
alter database add logfile group 5
('D:\OracleFiles\LogFiles\REDO4_A.LOG',
'E:\OracleFiles\LogFiles\REDO4_B.LOG')
size 20M;  --添加新的重做日志文件組
alter database add logfile member
'E:\OracleFiles\LogFiles\REDO4_C.LOG' to group 4;  --創建日志成員文件
alter database add logfile member
'D:\OracleFiles\LogFiles\REDO1_new.LOG' to 
('E:\app\Administrator\oradata\orcl\REDO01.LOG') ;  --指定成員名稱

---刪除
--日志成員
alter database drop logfile member 'E:\OracleFiles\LogFiles\REDO4_C.LOG';
--日志文件組
alter database drop logfile group 5;
--清空
alter database clear logfile group 4;

---更改
--關閉->復制源文件到目標位置->啟動加載但不打開mount
alter database rename file
  'D:\OracleFiles\LogFiles\REDO1_new.LOG',
  'D:\OracleFiles\LogFiles\REDO4_A.LOG'
to
  'E:\OracleFiles\LogFiles\REDO1_new.LOG',
  'E:\OracleFiles\LogFiles\REDO4_A.LOG';
--打開數據庫

--查看
--v$log v$logfile v$log_history

------4.4 歸檔日志文件
---切換
select log_mode from v$database;  --noarchivelog/archivelog
shutdown immediate;
startup mount;
alter database archivelog;
alter database open;

---進程
alter system set log_archive_max_processes = 3;

---位置
--本地
alter system set log_archive_dest_1='location=D:\OracleFiles\archive1 optional';
alter system set log_archive_dest_2='location=D:\OracleFiles\archive2 mandatory';
alter system set log_archive_dest_3='location=D:\OracleFiles\archive3 mandatory reopen=400';
alter system set log_archive_min_succeed_dest=3;  --最小歸檔數
alter system set log_archive_dest_state_4=defer;  --禁用位置
--遠程
alter system set log_archive_dest_1='service=MRKJ';

---查看
--v$database v$archived_log v$archive_dest v$archive_processes v$backup_redolog
archive log list;

----------5. 數據庫維護-------------
------5.1 數據庫控制
---事務
set transaction read only;  --read write
exec dbms_transaction.read_only;
set transaction use rollback segment system;  --分配回滾段
savepoint sp01;  --設置保存點
insert into jobs_temp values('DESIGN','DS',3000,5000);
rollback to sp01;  --回滾

---鎖
lock table dept_temp in row share mode;
--row exclusive mode/share mode/share row exclusive mode/exclusive mode

------5.2 數據導入/導出
---導出
create directory dump_dir as 'd:\dump';
grant read,write on directory dump_dir to scott;
--
expdp scott/1qaz2wsx directory=dump_dir dumpfile=tab.dmp tables=emp,dept
--模式
expdp system/1qaz2wsx directory = dump_dir dumpfile=schema.dmp schemas=scott,hr
--表空間
expdp system/1qaz2wsx directory = dump_dir dumpfile = tablespace.dmp tablespaces=tbsp_1
--數據庫
expdp system/1qaz2wsx directory=dump_dir dumpfile=fulldatabase.dmp full=y
--content/query/logfile/status

---導入
impdp system/1qaz2wsx directory=dump_dir dumpfile=tab.dmp 
tables=scott.dept,scott.emp remap_schema=scott:system  --
impdp system/1qaz2wsx directory=dump_dir dumpfile=schema.dmp 
schemas=scott remap_schema=scott:system;  --模式
impdp system/1qaz2wsx directory=dump_dir dumpfile=tablespace.dmp 
tablespaces=tbsp_1  --表空間
impdp system/1qaz2wsx directory=dump_dir dumpfile=fulldatabase.dmp full=y  --數據庫
--remap_schema/remap_tablesapce/sqlfile/table_exists_action/transport_datafiles

------SQL Loader
sqlldr --用法
---自由格式
/*  --student.ctl
load data
  infile 'd:\data\student.txt'
  into table student
  (stuno position(01:04) integer external,
   stuname position(11:14) char,
   sex position(21:22) char,
   old position(29:30) integer external
  )
*/
sqlldr system/1qaz2wsx control=d:\data\student.ctl log=d:\data\stu_log
---固定格式
/*  --persons.ctl
load data
infile 'd:\data\persons.csv'
append into table persons
fields terminated by ','
(code,name,sex,old)
*/
sqlldr system/1qaz2wsx control=d:\data\persons.ctl

 

注:部分SQL語句來源於《Oracle 11g從入門到精通(第2版)》——清華大學出版社


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM