© 逻辑运算符和谓词
in和not in 有哪些职员和分析员 SELECT ename,job
FORM emp
WHERE job IN ('clerk','analyst')
between和not between 哪些雇员的工资在2000和3000之间 SELECT ename,job,sal
FORM emp
WHERE sal BETWEEN 2000 AND 3000
like,not like SELECT ename,deptno
FORM emp
WHERE ename LIKE 'S%'
is null,is not null SELECT ename,job
FORM emp
WHERE comm IS NULL
© 数据操作
数据的插入 普通插入 INSERT INTO dept (empno,ename,deptno,empdate)
VALUES
(10,'accounting','new york',to_char(SYSDATE,'YYYY/MM/DD hh24:mi:ss') )
插入的时候同时查询 INSERT INTO dept (empno,ename,deptno,empdate)
VALUES
(10,'accounting',(SELECT deptno FROM depemp WHERE empno=10 AND rownum<=1),to_char(SYSDATE,'YYYY/MM/DD hh24:mi:ss') )
从其它表中选择插入数据 INSERT INTO emp (empno,ename,deptno)
SELECT id,name,department
FORM old_emp
WHERE department in(10,20,30,40)
插入空值(NULL) INSERT INTO dept VALUES(50,'education',NULL)
数据更新 UPDATE emp SET deptno=40,job='market rep' WHERE job='salesman'
数据删除 DELETE emp WHERE empno=765;
数据查询 等值连接 SELECT empno,ename,job,emp.deptno,dname
join FORM emp
JOIN dept ON emp.deptno=dept.deptno
等价于
SELECT empno,ename,job,emp.deptno,dname
FORM emp,dept
WHERE emp.deptno=dept.deptno
左外连接 SELECT m_user.user_cd,m_user.user_number,m_user.user_name
left (outer) join FORM m_user
LEFT OUTER JOIN m_user_account ON m_user.user_cd=m_user_account.user_cd
等价于
SELECT m_user.user_cd,m_user.user_number,m_user.user_name
FORM m_user,m_user_account
WHERE m_user.user_cd=m_user_account.user_cd(+)
右外连接 SELECT m_user.user_cd,m_user.user_number,m_user.user_name
right (outer) join FORM m_user
RIGHT JOIN m_user_account ON m_user.user_cd=m_user_account.user_cd
等价于
SELECT m_user.user_cd,m_user.user_number,m_user.user_name
FORM m_user,m_user_account
WHERE m_user.user_cd(+)=m_user_account.user_cd
全外连接 SELECT m_user.user_cd,m_user.user_number,m_user.user_name
full (outer) join FROM m_user
FULL JOIN m_user_account ON m_user.user_cd=m_user_account.user_cd
等价于
SELECT m_user.user_cd,m_user.user_number,m_user.user_name
FORM m_user,m_user_account
WHERE m_user.user_cd=m_user_account.user_cd(+)
UNION
SELECT m_user.user_cd,m_user.user_number,m_user.user_name
FORM m_user,m_user_account
WHERE m_user.user_cd(+)=m_user_account.user_cd
非等值连接 SELECT ename,sal
FORM emp,salgrade
WHERE salgrade.grade=3 and emp.sal between salgrade.losal and salgrade.hisal
子查询 SELECT ename,deptno
FORM emp
WHERE deptno= (SELECT deptno FORM emp WHERE ename='smith')
字符串拼接 SELECT recvwork_user_cd || '_GP' FROM t_receivework
使用CASE语句 SELECT
(
CASE
WHEN recvwork_grouping_cd='GP0001' THEN to_char(recvwork_user_cd || '_GP1')
WHEN recvwork_grouping_cd='GP0002' THEN to_char(recvwork_user_cd || '_GP2')
ELSE to_char(recvwork_user_cd || '_GPN')
END
) AS recvwork_user_cd
FROM t_receivework
取 TOP N 行 SELECT * FROM cat WHERE ROWNUM<=N
取N1-N2行 SELECT emName,emNo FROM
( SELECT ROWNUM ROWSEQ,emName,emNo FROM cat )
WHERE ROWSEQ BETWEEN N1 AND N2
使用Group和Having SELECT recvwork_user_cd, count(*) AS workcount
FROM t_receivework
GROUP BY recvwork_user_cd HAVING count(*)>2
使用Exists语句 SELECT * FROM t_receive
WHERE EXISTS (
SELECT * FROM t_receivework_request
WHERE t_receive.receive_cd=t_receivework_request.receive_cd
AND t_receivework_request.contact_grouping_cd='GP0001' )
union运算 返回一个查询结果中有但又不重要的行,它将基表或视图中的记录合并在一起 SELECT ename,sal FORM account WHERE sal>2000
UNION
SELECT ename,sal FORM research WHERE sal>2000
intersect运算 返回查询结果中相同的部分 SELECT job FORM account
INTERSECT
SELECT job FORM research
minus运算 返回在第一个查询结果中与第二个查询结果不相同的那部分行记录 SELECT job FORM account
MINUS
SELECT job FORM sales;
© ORACLE系统函数
字符型函数 initcap(ename) 将ename中每个词的第一个字母改为大写
length(ename) 计算字符串的长度
substr(job,1,4) 取子字符串。如果job值为hello world,则值为hell
lower 变为小写的字符串
upper 变为大写的字符串
least 取出字符串列表中按字母排序排在最前面的一个串
greatest 取出字符串列表中按字母排序排在最后的一个串
instr(字段名,'字符串')>0 是否在字符串中
日期函数 add_month(hiredate,5) 在hiredate时间上加5个月
month_between(sysdate,hiredate) 计算hiredate时间与系统时间之间相差的月数
next_day(hiredate,'FRIDAY') 计算hiredate日期之后的第一个星期五的日期
日期 = to_date(字符串,格式)
to_date('2001-08-01','YYYY-MM-DD')
字符串 = to_char(日期,格式)
to_char(SYSDATE,'YYYY/MM/DD hh24:mi:ss')
D 一周中的星期几
DAY 天的名字,使用空格填充到9个字符
DD 月中的第几天
DDD 年中的第几天
DY 天的简写名
IW ISO标准的年中的第几周
IYYY ISO标准的四位年份
YYYY 四位年份
YYY,YY,Y 年份的最后三位,两位,一位
HH 小时,按12小时计
HH24 小时,按24小时计
MI 分
SS 秒
MM 月
Mon 月份的简写
Month 月份的全名
W 该月的第几个星期
WW 年中的第几个星期
当前时间减去7分钟的时间;
select sysdate - interval '7' MINUTE from dual;
当前时间减去7小时的时间;
select sysdate - interval '7' hour from dual;
当前时间减去7天的时间;
select sysdate - interval '7' day from dual;
当前时间减去7月的时间;
select sysdate - interval '7' month from dual;
当前时间减去7年的时间;
select sysdate - interval '7' year from dual;
时间间隔乘以一个数字;
select sysdate - 8 *interval '2' hour from dual;
select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual;
select to_char(sysdate, 'yyyy-mm-dd hh:mi:ss') from dual;
select to_char(sysdate, 'yyyy-ddd hh:mi:ss') from dual;
select to_char(sysdate, 'yyyy-mm iw-d hh:mi:ss') from dual;
算术函数 least(v1,v2)
trunc(sal,0) 取sal的近似值(截断)
avg(sal) 计算sal的平均值
stddev(sal) 计算sal的平均差
sum(sal) 计算sal的总值
空值函数 nvl(v1,v2) NVL(EXPR1, EXPR2)函数
解释:
IF EXPR1=NULL
RETURN EXPR2
ELSE
RETURN EXPR1
switch语句 DECODE(AA,V1,R1,V2,R2...) IF AA=V1 THEN RETURN R1
IF AA=V2 THEN RETURN R2
..…
ELSE
RETURN NULL
补位函数 LPAD(char1,n,char2) 字符char1按制定的位数n显示,不足的位数用char2字符串替换左边的空位
聚组函数 count(comm) select count(distinct job) from emp
min(comm) 最小值
max (comm) 最大值
列名 select * from USER_COL_COMMENTS u where u.table_name = 'M_NAME'
分页 SELECT * FROM
(
SELECT A.*, rownum r
FROM
(
XXXXXXXXXXX
) A
WHERE rownum <= PageUpperBound
) B
WHERE r > PageLowerBound;
© 关于表、View和索引的操作
创建表 CHAR 固定长度的字符串 CREATE TABLE dept (deptno number(2) not null, dname char(14), loc char(13));
VARCHAR2 可变长度的字符串
NUMBER(M,N)
数字型M是位数总长度, N是小数的长度
DATE 日期类型
默认值 DEFAULT SYSDATE
不允许重复 UNIQUE
关键字 PRIMARY KEY
修改表 改变表的名称 ALTER TABLEdept add (headcnt number(3));
ALTER TABLE 表名1 TO 表名2; ALTER TABLEdept modify dname char(20);
ALTER TABLEdept modify (loc char(12));
在表的后面增加一个字段 ALTER TABLEdept modify loc char(12);
ALTER TABLE表名 ADD 字段名 字段名描述; ALTER TABLEdept modify (dname char(13),loc char(12));
修改表里字段的定义描述
ALTER TABLE表名 MODIFY字段名 字段名描述;
给表里的字段加上约束条件
ALTER TABLE 表名 ADD CONSTRAINT 约束名 PRIMARY KEY (字段名);
ALTER TABLE 表名 ADD CONSTRAINT 约束名 UNIQUE (字段名);
把表放在或取出数据库的内存区
ALTER TABLE 表名 CACHE;
ALTER TABLE 表名 NOCACHE;
删除表 DROP TABLE dept
清空表里的所有记录, 保留表的结构 TRUNCATE dept
创建View CREATE VIEW mydept (person,title,salary)
AS
SELECT ename,job,sal
FORM emp
WHERE deptno=10;
删除View DROP VIEW mydept
建立索引 CREATE INDEX emp_ename ON emp(ename)
create index IDX_TD50030_1 on TD50030 (shiharai_taisyou_ym,shiharai_dairiten_c,dairiten_c) tablespace USER_IDX01;
删除索引 DROP INDEX emp_ename
建立同义词 CREATE SYNONYM同义词名FOR 表名;
CREATE SYNONYM同义词名FOR 表名@数据库链接名;
© 事务
更新的提交 commit[WORK]
更新取消 rollback[WORK]
保存当前点 savepoint 标记名
自动提交方式 SET autocommit on
如果状态设为开,则使用inesrt,update,delete会立即提交。
© 触发器、存储过程、函数、游标
触发器 触发器是一种特殊类型的存储过程,触发器是自动的执行的,当使用一种或多种数据修改操作(UPDATE、INSERT 或 DELETE)在指定表中对数据进行修改时,触发器会生效。触发器可以查询其它表,而且可以包含复杂的 SQL 语句。它们主要用于强制复杂的业务规则或要求,还有助于强制引用完整性。在调试程序时触发器可能成为干扰,因此需要集中对它文档化。 --新建触发器的语法--
CREATE OR REPLACE TRIGGER <trigger_name>
在Oracle数据库中,触发器创建后,可以从表的Tirgger中查看。在写触发器的语句中,用:OLD表示操作前的数据,用:NEW表示操作后的数据。 <BEFORE | AFTER> <ACTION> ON <table_name>
编写触发器的过程中,要注意不要漏掉个别分号。 DECLARE
<variable definitions>
BEGIN
<trigger_code>
EXCEPTION
<exception clauses>
END ;
--使能用或者不能用--
ALTER TRIGGER <trigger_name> DISABLE/ENABLE
--删除--
DROP TRIGGER <trigger_name>
--例子--
CREATE OR REPLACE TRIGGER upd_test
AFTER UPDATE OF ENAME ON EMP
FOR EACH ROW
BEGIN
INSERT INTO EMPHISTORY(empno,EOLDNAME,ENEWNAME)
VALUES (:OLD.empno,:OLD.ENAME,:NEW.ENAME);
END;
存储过程 存储过程是由流控制和SQL语句书写的过程,这个过程经编译和优化后存储在数据库服务器中,使用时只要调用即可。存储过程具有执行速度快、能保证数据的安全性和完整性等特点。 --新建存储过程的语法--
存储过程的执行和触发器和函数不一样,是要在Java中手动执行的。Java调用存储过程的方法,请见这里。 CREATE OR REPLACE PROCEDURE procedure_name
<input or output variable definitions>
AS
<variable definitions>
BEGIN
<procedure_code>
EXCEPTION
<exception clauses>
END;
--例子-------1-----
CREATE OR REPLACE PROCEDURE drop_class
( arg_student_id IN varchar2, arg_class_id IN varchar2, status OUT number )
AS
counter number ;
BEGIN
status := 0 ;
select count (*) into counter from student_schedule where student_id = arg_student_id and class_id = arg_class_id ;
IF counter = 1 THEN
delete from student_schedule where student_id = arg_student_id and class_id = arg_class_id ;
status := -1 ;
END IF;
END;
--例子-------2-----
在Oracle中建执行插入操作的存储过程:
create or replace procedure insert_user_information
(
p_user_login_name in varchar2,
p_user_password in varchar2,
p_user_name in varchar2,
p_user_telephone in varchar2,
p_user_type in number,
p_out out number
) as
v_count number;
begin
if p_user_login_name is null or p_user_password is null then
p_out:=-1; --用户名和密码不能为空,
return ;
end if;
if p_user_type is null then p_out:=-2; --用户类型不能为空
return ;
end if;
select count(*) into v_count from user_information a where .user_login_name=upper(p_user_login_name);
if v_count>0 then
p_out:=-3; --该用户名已经存在
return ;
end if;
insert into user_information
values(seq_user_information.nextval,upper(p_user_login_name), p_user_password,p_user_name,p_user_telephone,p_user_type, sysdate,sysdate);
commit;
p_out:=0; --操作成功
return ;
exception
when others then
p_out:=-4; --插入过程中出现异常
return ;
end ;
--例子-------3-----
可以做到,虽然有点繁。
你可以在一个Package 中定义一个Cursor myCursor类,
type c_offer is ref cursor return V_offer_other%rowtype;
然后在
procedure get_other_offers(e_id in varchar2,whereClause in varchar2,rc out c_offer);
这样就返回了一个Cursor.
在java中条用时要
import oracle.jdbc.driver.*
.....
cstmt.registerOutParameter(3,OracleTypes.CURSOR);
cstmt.execute();
rst=(ResultSet)cstmt.getObject(3);
自定义函数 和系统函数一样,你也可以自定义函数。函数的返回类型可以是单一值,也可以是一张表。 --新建函数的语法--
CREATE [OR REPLACE] FUNCTION function_name
<input or output variable definitions>
RETURN return_type {IS | AS}
BEGIN
<function_code>
EXCEPTION
<exception clauses>
END;
--例子--
CREATE OR REPLACE FUNCTION getSameName(sameEname IN varchar2)
RETURN NUMBER
IS
samecount NUMBER;
BEGIN
Select count(*) INTO samecount FROM emp WHERE ename = sameEname;
RETURN (samecount);
END;
SELECT ename,getSameName(ename) FROM Emp
游标 游标是用来处理使用SELECT语句从数据库中检索到的多行记录的工具。借助于游标的功能,数据库应用程序可以对一组记录逐个进行处理,每次处理一行。 显式游标 游标的FOR循环
语法
打开游标 for <记录名> in <游标名> loop
open <游标名> 例 open color_cur; <一组命令>
end loop;
游标属性
%notfound 其中:
%found 索引是建立在每条记录的值之上的;记录名不必声明;每个值对应的是记录名,列名;初始化游标指打开游标;
%rowcount 活动集合中的记录自动完成FETCH操作;退出循环,关闭游标
%isopen
例 隐式游标
fetch my_cur into my_var;
while my_cur %found loop 隐式游标是指SQL命令中用到的,没有明确定义的游标
(处理数据) insert,update,delete,select语句中不必明确定义游标
fetch my_cur into my_var; 调用格式为SQL%
exit when my_cur %rowcount=10; 存贮有关最新一条SQL命令的处理信息
end loop;
隐式游标的属性
%notfound属性 隐式游标有四个属性
取值情况如下: SQL%NOTFOUND
fetch操作没有返回记录,则取值为true SQL%FOUND
fetch操作返回一条记录,则取值为false SQL%ROWCOUNT:隐式游标包括的记录数
对游标无fetch操作时,取值为null 例:
<游标名> %notfound delete from baseball_team where batting_avg<100;
if sql%rowcount>5 then
例 insert into temp values('your team needs help');
if color_cur %notfound then... end if;
注:如果没有fetch操作,则<游标名> %notfound将导致出错,
因为%notfound的初始值为NULL。 SQL%ISOPEN:取值总为FALSE。
关闭游标 SQL命令执行完毕,PL/SQL立即关闭隐式游标。
close <游标名> 例 close color_cur;
© ORACLE内部变量和方法
TAB 用户创建的所有基表、视图和同义词清单 SELECT * FORM tab;
DTAB 构成数据字典的所有表
COL 用户创建的基表的所有列定义的清单
CATALOG 用户可存取的所有基表清单
describe 描述基表的结构信息 describe dept
© 权限管理
1.创建用户
CREATE USER mydbuser IDENTIFIED BY mydbuser
2.GRANT 赋于权限
常用的系统权限集合有以下三个:
CONNECT(基本的连接), RESOURCE(程序开发), DBA(数据库管理)
常用的数据对象权限有以下五个:
ALL ON 数据对象名, SELECT ON 数据对象名, UPDATE ON 数据对象名,
DELETE ON 数据对象名, INSERT ON 数据对象名, ALTER ON 数据对象名
GRANT CONNECT, RESOURCE TO 用户名;
GRANT SELECT ON 表名 TO 用户名;
GRANT SELECT, INSERT, DELETE ON表名 TO 用户名1, 用户名2;
3.REVOKE 回收权限
REVOKE CONNECT, RESOURCE FROM 用户名;
REVOKE SELECT ON 表名 FROM 用户名;
REVOKE SELECT, INSERT, DELETE ON表名 FROM 用户名1, 用户名2;
4.查询每个用户的权限
SELECT * FROM DBA_SYS_PRIVS;
© 数据导出
1 将数据库TEST完全导出,用户名system 密码manager 导出到D:\daochu.dmp中
exp system/manager@TEST file=d:\daochu.dmp full=y
2 将数据库中system用户与sys用户的表导出
exp system/manager@TEST file=d:\daochu.dmp owner=(system,sys)
3 将数据库中的表inner_notify、notify_staff_relat导出
exp aichannel/aichannel@TESTDB2 file= d:\data\newsmgnt.dmp tables=(inner_notify,notify_staff_relat)
4 将数据库中的表table1中的字段filed1以"00"打头的数据导出
exp system/manager@TEST file=d:\daochu.dmp tables=(table1) query=\" where filed1 like '00%'\"
5 将T1.dmp的数据导入用户KQA1中
imp KQA1/KQA1@orcl FILE=T1.DMP LOG=T1IMP.LOG FULL=Y SHOW=Y
6.抽出索引创建语句
expdp xu/xu directory=dp_dir dumpfile=ind.dmp include=index
impdp xu/xu directory=dp_dir dumpfile=ind.dmp sqlfile=ind.sql
© Flash Back
1.启用闪回数据库特性
startup mount;
alter database archivelog;
# archive log start;
alter database flashback on;
alter database open;
alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
SELECT OLDEST_FLASHBACK_SCN, OLDEST_FLASHBACK_TIME FROM V$FLASHBACK_DATABASE_LOG;
select * from V$FLASH_RECOVERY_AREA_USAGE
2.获得当前数据库的SCN值
select dbms_flashback.get_system_change_number fscn from dual; (9I 10G)
select current_scn from v$database;
3.闪回日志
/data5/flash_recovery_area/EYGLE/flashback
4.进行闪回操作
shutdown immediate;
startup mount;
alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
select * from V$FLASHBACK_DATABASE_LOG;
flashback database to timestamp to_timestamp ('2005-03-29 17:02:28','yyyy-mm-dd hh24:mi:ss');
5.resetlogs打开数据库
shutdown immediate;
startup mount;
#alter database open resetlogs;
alter database open noresetlogs
select * from v$log;
6.设置闪回地址,大小,过期时间
alter system set db_recovery_file_dest='/flash_recovery_area';
alter system set db_recovery_file_dest_size=3G;
alter system set db_flashback_retention_target=240
alter database flashback on;
select flashback_on from v$database;
7.闪回能够回到的最大SCN
select oldest_flashback_scn, oldest_flashback_time from v$flashback_database_log;
8.flashback的代价(每小时必要的IO)
select end_time,flashback_data,db_data,redo_data from v$flashback_database_stat;
9.查看当前闪回的大小
select * from v$sgastat where name like 'flashback%';
10.闪回到某个SCN或者Sequence
select dbms_flashback.get_system_change_number c_SCN from dual;
flashback database to scn=2728665;
flashback database to sequence=2123 thread=1;
11.两天前的数据
select * from employees as of timestamp (sysdate - 2);
12.用SCN 查询
select * from employees as of SCN ;
13.表的删除和恢复:
flashback table order_items to before drop rename to order_items_old_version;
14.使用flash table
create table test as select * from dba_users;
select count(*) from test as of scn 12742550;
select count(*) from test as of timestamp to_timestamp('21-07-09 14:20:00', 'dd-mm-yy hh24:mi:ss');
alter table test enable row movement;
flashback table test to scn 1391833;
flashback table test to timestamp to_timestamp('22-07-09 13:20:00', 'dd-mm-yy hh24:mi:ss');
15.对table的flashback
flashback table t_user to before drop;
drop table t_user purge;
drop tablespace small including contents and datafiles;
purge table t_user;
purge user_recyclebin;
purge dba_recyclebin;
16.查看Undo信息
select begin_time,end_time, undoblks, maxquerylen,ssolderrcnt,nospaceerrcnt from v$undostat;
17.使用还原点
create restore point restore_point_01 guarantee flashback database;
drop restore point restore_point_01;
flashback database to restore point restore_point_01;
18.使用回收站
show recyclebin;
select count(*) from dba_recyclebin where owner='DROPPER';
select owner, original_name, type, droptime, can_undrop, space from dab_recyclebin;
select object_name, original_name, type from user_recyclebin;
select sum(bytes) from dba_free_space where tablespace_name='SMALL';
select segment_name, bytes from dba_segments where tablespace_name='SMALL';
© RMAN
1.连接到rman
rman target sys/necsthz
2.不备份索引表空间
configure exclude for tablespace smsafeindex;
3.自动备份控制文件
configure controlfile autobackup on;
recover database until cancel using backup controlfile;
backup as copy current controlfile;
backup as backupset current controlfile;
backup tablespace system include current controlfile;
configure controlfile autobackup on;
4.进行0级增量备份
backup incremental level 0 database;
5.做增量0的备份压缩集,不包括索引表空间
backup incremental level 0 as compressed backupset database;
6.进行1级增量备份
backup incremental level 1 differential database;
7.做增量1备份
backup incremental level 1 as compressed backupset database;
8.进行1级累计备份
backup incremental level 1 cumulative database;
9.做增量1积累备份
backup incremental level 1 cumulative as compressed backupset database;
10.用增量备份更新映像副本
①backup as copy incremental level 0 database tag db_whole_copy;
②run{
allocate channel d1 type disk;
backup incremental level 1
for recover of copy with tag db_whole_copy
database tag db_copy_upd;
recover copy of database with tag db_whole_copy;
delete backupset tag db_copy_upd;}
11.备份全库并删除旧的归档日志
backup database plus archivelog delete input;
12.备份指定表空间
backup tablespace system plus archivelog delete input;
13.备份归档日志
backup archivelog all delete input;
14.查看备份
list backup;
15.验证备份
validate backupset 6;
16.基于时间点的恢复
set DBID=1454675292
startup nomount;
restore controlfile from autobackup;
alter database mount;
restore database until time "TO_DATE('03/14/07 15:00:00','MM/DD/YY HH24:MI:SS')";
recover database until time "TO_DATE('03/14/07 15:00:00','MM/DD/YY HH24:MI:SS')";
alter database open resetlogs;
17.基于cancel恢复
recover database until cancel;
recover database until change 309121;
18.restore数据库
restore database skip tablespace smsafeindex;
19.recover数据库
recover database skip forever tablespace smsafeindex;
20.Report
report schema;列出所有的用户和配置文件
report need backup; --列出未备份
report need backup days 3; --列出3天未备份的文件
report need backup redundancy 3; --少于3个备份的所有文件
report obsolete; --列出不再需要的副本
report obsolete redundancy 2; --备份数至少为3的备份
21.查看表空间的备份情况
list backup;
list backup of database;
list backup of datafile 4;
list backup of datafile 4 summary;
list backup of tablespace users;
list backup of controlfile;
list backup of archivelog all;
list backup of archivelog from sequence 1000 until sequence 1050;
list copy;
list copy of archivelog from time='sysdate-7';
22.删除并重建索引表空间
drop tablespace smsafeindex including contents;
create tablespace smsafeindex datafile 'd:\oracle\product\10.2.0\orcl\smsafeindex01.dbf' size 1G;
23.删除不要的备份
delete obsolete; --删除不要的备份
delete obsolete redundancy 2; --删除过多的备份
delete copy of datafile 6 tag file6_extra;
24.crosscheck
crosscheck archivelog from time="to_date('2008-5-20','yyyy-mm-dd')" until time="to_date('2008-5-23','yyyy-mm-dd')";
crosscheck archivelog all; 检查控制文件和实际物理文件的差别。
delete expired archivelog all; 同步控制文件的信息和实际物理文件的信息。
25.允许删除超过90天的备份
backup datafile 7 keep until time "sysdate+90" nologs;
26.用Rman创建duplicate数据库
rman target sys/oracle@orcl auxiliary sys/oracle@aux
duplicate target database to aux;
27.TSPITR
rman target /
recover tablespace users, example until time '2006-03-31:08:00:00' auxiliary destination '/u01/app/oracle/oradata/aux';
alter tablespace users online;
alter tablespace example online;
28.脚本
create script XXX
{
backup database;
}
create global script XXX1
{
backup database;
}
run
{
execute script XXX;
}
print script XXX;
29.特定脚本
○备份到时间点
run {
shutdown immediate;
startup mount;
set until sequence 10305 thread 1;
restore database;
recover database;
alter database open resetlogs;}
○备份到磁带
run {
allocate channel 'omni_0' type 'sbt_tape'
parms 'ENV=(OB2BARTYPE=Oracle8,OB2APPNAME=ocp10g,OB2BARLIST=test1)';
allocate channel 'omni_1' type 'sbt_tape'
parms 'ENV=(OB2BARTYPE=Oracle8,OB2APPNAME=ocp10g,OB2BARLIST=test1)';
backup incremental level 0 filesperset 1
format 'test1.dbf'
database;
}
○从磁盘一道磁带
run {
allocate channel t1 type sbt_tape;
allocate channel t2 type sbt_tape;
backup copy of database delete input;
backup archivelog all delete all input;
release channel t1;
release channel t2;
allocate channel d1 type disk;
allocate channel d2 type disk;
backup as copy database;
release channel d1;
release channel d2;}
○创建备份集(469/569) 单个通道,8小时内备份,二进制压缩
run {
allocate channel d1 type disk;
backup as compressed backupset
format '/u06/ocp10g/backup/%d_%u.dbf'
duration 8:00 minimize load
filesperset 1
database;
sql 'alter system archive log current';
backup as compressed backupset
format '/u06/ocp10g/backup/%d_%u.arc'
duration 8:00 minimize time
archivelog all delete all input;}
○保留超过一周的归档日志到磁带
run {
allocate channel t1 type sbt;
backup as backupset archivelog
until time 'sysdate - 7';}
○脱机备份
run {
shutdown immediate;
startup mount;
backup as backupset database;
alter database open;}
○备份用户空间
run {
allocate channel d1 type disk
maxpiecesize 50m;
backup as compressed backupset
format 'E:\oracle\backup\%U.dbf'
tablespace users;}
○将当前的控制文件备份到一个备份集
run {allocate channel d1 type disk;
backup as backupset format 'E:\oracle\backup\%U.ctl'
current controlfile;}
© 正则表达式
(1)'^' 匹配输入字符串的开始位置,在方括号表达式中使用,此时它表示不接受该字符集合。
'$' 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 'n' 或 'r'。
'.' 匹配除换行符 n之外的任何单字符。
'?' 匹配前面的子表达式零次或一次。
'*' 匹配前面的子表达式零次或多次。
'+' 匹配前面的子表达式一次或多次。
'( )' 标记一个子表达式的开始和结束位置。
'[]' 标记一个中括号表达式。
'{m,n}' 一个精确地出现次数范围,m=<出现次数<=n,'{m}'表示出现m次,'{m,}'表示至少出现m次。
'|' 指明两项之间的一个选择。例子'^([a-z]+|[0-9]+)$'表示所有小写字母或数字组合成的字符串。
-2
字符簇:
[[:alpha:]] 任何字母。
[[:digit:]] 任何数字。
[[:alnum:]] 任何字母和数字。
[[:space:]] 任何白字符。
[[:upper:]] 任何大写字母。
[[:lower:]] 任何小写字母。
[[:punct:]] 任何标点符号。
[[:xdigit:]] 任何16进制的数字,相当于[0-9a-fA-F]。
-3
regexp_like(x,pattern[,match_option])
match_option可以有如下几种形式:
1.'c' 表明进行匹配时区分大小写(这也是默认选项)
2.'i' 表明在匹配时不区分大小写
3.'n' 表明允许使用匹配任何字符串的元数据,即'.'
4.'m' 将x作为一个包含多行的字符串
这个例子是寻找员工中的80后的员工
select * from emp where regexp_like(to_char(birthdate,’yyyy’),’^198[0-9]$’);
这个例子是寻找名字是以’M'或者’m'打头的那些员工的名字
select * from emp where regexp_like(ename,’^j’,'i’)
-4
regexp_instr(x,pattern[,start[,occurrence[,return_option[,match_option]]]])
1. x 待匹配的字符串
2. pattern 待匹配的模式
3. start 开始匹配的位置,如果不指定默认为1
4. occurrence 匹配的次数,如果不指定,默认为1
5. return_option 指定返回值的类型,如果该参数为0,则返回值为匹配位置的第一个字符,如果该值为非0则返回匹配值的最后一个位置
6. match_option 可以用这个参数来修改一些默认的配置设置这个值与前面所说的regexp_like函数中的match_option参数的意义是一样的
(1)select regexp_instr('i love oracle','o[[:alpha:]]{4}e$') as r from dual;
以o开头,以e结尾,在o和e之间有4个字符的字符串
(2)select regexp_instr('The total is $400 for your purchase.','$[[:digit:]]+') from dual;
$400在字符串的开始位置
select q'(amar's web blog. It's personal.)' str from dual;
select q'[amar's web blog. It's personal.]' str from dual;
select q'Aamar's web blog. It's personal.A' str from dual;
select q'/amar's web blog. It's personal./' str from dual;
select q'Zamar's web blog. It's personal.Z' str from dual;
select q'|amar's web blog. It's personal.|' str from dual;
select q'+amar's web blog. It's personal.+' str from dual;
insert into am102(col1, col2) values (1,q'[amar's web blog. It's personal]')
insert into am102(col1, col2) values (2,q'[this is a simple string]')
insert into am102(col1, col2) values (3,q'[this is just another string]')
© 有用的SQL语句
select table_name from user_tables; ##获取数据库的全部表
select * from all_users; ##查看所有用户
select name from v$database; ##查看当前数据库名
select * from v$instance; ##查看所有的数据库实例
select username,password from dba_users; ##查看当前实例中的用户和密码
select member from v$logfile; ##查看日志文件
select * from user_role_privs; ##查看当前用户的角色
select username,default_tablespace from user_users; ##查看当前用户的缺省表空间
查找数据库中所有列
select C.column_name,C.TABLE_NAME from dba_tab_columns C where owner=''
表复制
insert into table_a (id,name,age) select b.id,b.name,b.age from table_b;
查看当前Job的执行计划
select job,next_date,next_sec,failures,broken from user_jobs;
删除一个job
begin
dbms_job.remove(46);--46为job号
end;
查看当前库的所有数据表:
select TABLE_NAME from all_tables;
select * from all_tables;
select table_name from all_tables where table_name like ‘u’;
创建用户并赋予权限
create user mpss
identified by "mpss12"
default tablespace TS_MPSS_DATA
temporary tablespace TEMP;
建立临时表空间
CREATE
TEMPORARY TABLESPACE "SWVIP" TEMPFILE '/app/oracle/oradata/
sworacle/SWVIP.dbf' SIZE 5M EXTENT MANAGEMENT LOCAL UNIFORM
SIZE 1M
create tablespace TS_MPSS_DATA datafile '/mpss/data/ts_mpss_data.bdf ' size 1024m autoextend on ;
查看表空间大小
SELECT D.TABLESPACE_NAME "Name",
TO_CHAR(((((A.BYTES - DECODE(F.BYTES, NULL, 0, F.BYTES)) / 1024 / 1024)) /(A.BYTES / 1024 / 1024))*100,'99,990.9') "used(%)",
TO_CHAR((DECODE(F.BYTES, NULL, 0, F.BYTES) / 1024 / 1024),'999,990.9') "Free (M)"
FROM SYS.DBA_TABLESPACES D, SYS.SM$TS_AVAIL A, SYS.SM$TS_FREE F
WHERE D.TABLESPACE_NAME = A.TABLESPACE_NAME
AND F.TABLESPACE_NAME (+) = D.TABLESPACE_NAME;
SELECT D.TABLESPACE_NAME,SPACE "SUM_SPACE(M)",BLOCKS SUM_BLOCKS,SPACE-NVL(FREE_SPACE,0) "USED_SPACE(M)",
ROUND((1-NVL(FREE_SPACE,0)/SPACE)*100,2) "USED_RATE(%)",FREE_SPACE "FREE_SPACE(M)"
FROM
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES)/(1024*1024),2) SPACE,SUM(BLOCKS) BLOCKS
FROM DBA_DATA_FILES
GROUP BY TABLESPACE_NAME) D,
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES)/(1024*1024),2) FREE_SPACE
FROM DBA_FREE_SPACE
GROUP BY TABLESPACE_NAME) F
WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME(+)
UNION ALL --if have tempfile
SELECT D.TABLESPACE_NAME,SPACE "SUM_SPACE(M)",BLOCKS SUM_BLOCKS,
USED_SPACE "USED_SPACE(M)",ROUND(NVL(USED_SPACE,0)/SPACE*100,2) "USED_RATE(%)",
NVL(FREE_SPACE,0) "FREE_SPACE(M)"
FROM
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES)/(1024*1024),2) SPACE,SUM(BLOCKS) BLOCKS
FROM DBA_TEMP_FILES
GROUP BY TABLESPACE_NAME) D,
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES_USED)/(1024*1024),2) USED_SPACE,
ROUND(SUM(BYTES_FREE)/(1024*1024),2) FREE_SPACE
FROM V$TEMP_SPACE_HEADER
GROUP BY TABLESPACE_NAME) F
WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME(+) ;
查看表空间物理文件的名称及大小;
select tablespace_name, file_id, file_name,
round(bytes/(1024*1024),0) total_space
from dba_data_files
order by tablespace_name;
查看数据文件放置的路径
col file_name format a50
select tablespace_name,file_id,bytes/1024/1024,file_name from dba_data_files order by file_id;
查看数据库库对象
select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status;
检查被长时间锁的对象
select a.session_id,a.process,a.locked_mode,b.object_name,b.object_type,b.status from v$locked_object a,dba_objects b where a.object_id=b.object_id;
用系统管理员,查看当前数据库有几个用户连接:
select username,sid,serial# from v$session;
扩表空间
alter tablespace G000 add datafile '/dev/vgbilling/rg000_lv03' SIZE 7500m;
创建DB Link
CREATE DATABASE LINK LK_KQA CONNECT TO KQA1 IDENTIFIED BY KQA1 USING 'ORCL';
创建Materialized View
create materialized view FRAME refresh fast for update as select
ACCOMMODATION_AREA_CODE,
FACILITY_NAME,
FACILITY_NUMBER,
DEVICE_NUMBER,
FACILITY_TYPE,
COUPLER_TYPE,
FLOOR_NAME,
FLOOR_GROUP,
FLOOR_FRAME_NUMBER,
REAL_ACCOMMODATE_BIL_CODE
from k027.FRAME@k027
where ACCOMMODATION_AREA_CODE = '27205001';
sequence使用
create sequence seq_product INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE CACHE 10;
--seq_product.CURRVAL
--seq_product.NEXTVAL
建表语句
CREATE TABLE CENTER_ACROSS_INFO (
ACCOMMODATION_AREA_CODE VARCHAR2(24) NOT NULL ,
FACILITY_NAME VARCHAR2(30) NOT NULL ,
FACILITY_NUMBER VARCHAR2(39) NOT NULL);
ALTER TABLE CENTER_ACROSS_INFO ADD COLUMN DEVICE_NUMBER VARCHAR(30);
ALTER TABLE CENTER_ACROSS_INFO ALTER COLUMN DEVICE_NUMBER NUMBER(2,4);
ALTER TABLE CENTER_ACROSS_INFO DROP COLUMN DEVICE_NUMBER ;
ALTER TABLE CENTER_ACROSS_INFO ADD CONSTRAINT
CENTER_ACROSS_INFO_PK PRIMARY KEY (ACCOMMODATION_AREA_CODE, FACILITY_NAME);
--DROP TABLE CENTER_ACROSS_INFO;
建立表空间
create tablespace DATA
datafile
'd:/DATA/data01.dbf' size 512M reuse autoextend off
extent management local uniform size 10M
segment space management auto;
alter tablespace DATA add datafile 'd:/DATA/data02.dbf' size 512M;
打开监听
lsnrctl start
进入ARCHIVELOG模式
startup mount
alter database archivelog;
alter database open;
archive log list;
archive log all;
select log_mode from v$database;
丢失control文件恢复
alter system set control_files="E:\ORACLE\PRODUCT\10.1.0\ORADATA\ORCL\CONTROL02.CTL" scope=spfile;
startup force;
select * from v$controlfile;
select recid,name,thread#,sequence# from v$archived_log
丢失数据文件恢复
create tablespace noncrit datafile 'E:\oracle\product\10.1.0\oradata\orcl\noncrit.dbf' size 2m;
create table ex203 (c1 date) tablespace noncrit;
insert into ex203 values(sysdate);
alter database datafile 7 online;
alter database datafile 3 offline;
建立一个备份控制文件
Alter database backup control file to trace.
启动记录转移
alter table dept enable row movement;
alter table emp enable row movement;
flashback table emp,dept to timestamp to_timestamp('21-07-09 14:20:00', 'dd-mm-yy hh24:mi:ss');
flashback table emp,dept to scn 6539425 enable triggers;
查看连接
select sid,username,program from v$session;
测试instance是否能够连的上
tnsping qnetdb
查看系统参数
SQL>show parameter mttr
fast_start_mttr_target integer 300
这个参数说明当instance recovery 的时候,数据库能够在300s之内open。
show parameter recovery
show parameter db_recovery
show parameter log_archive_dest
alter system set fast_start_mttr_target=0;
查询某个SQL语句执行用的cpu时间
select count(*) from dba_objects,dba_objects;
select cpu_time,elapsed_time,disk_reads from v$sql where sql_text='select count(*) from dba_objects,dba_objects ';
查询alert信息
select reason,metric_value from dba_outstanding_alerts;
加快创建索引
create index xu.rname_idx on xu.regions(region_name) tablespace indx parallel 8;
create index xu.rname_idx on xu.regions(region_name) tablespace indx nologging;
查看table的历史记录
select name, versions_startscn,versions_endscn from countries versions between scn minvalue and maxvalue;
create table countries (name varchar2(50));
insert into countries values ('hello');
insert into countries values ('tba');
update countries set name='abc' where name='tba'
alter table countries enable row movement;
flashback table countries to scn 12776941 enable triggers;
获得表空间的名字
select distinct FILE_NAME, TABLESPACE_NAME from dba_data_files;
select owner,table_name,tablespace_name from all_tables where tablespace_name='USERS';
select extent_id, file_id, block_id, blocks from dba_extents where owner='XU' and segment_name='USERS';
select
a.tablespace_name "Name",
round(a.bytes_alloc/1024/1024,2) "all(M)",
round((a.bytes_alloc-nvl(b.bytes_free,0))/1024/1024,2) "used(M)",
round(nvl(b.bytes_free,0)/1024/1024,2) "free(M)",
round((nvl(b.bytes_free,0)/a.bytes_alloc)*100,2) "free(%)"
from (select f.tablespace_name,
sum(f.bytes) bytes_alloc,
sum(decode(f.autoextensible,'YES',f.maxbytes,'NO',f.bytes)) maxbytes
from dba_data_files f
group by tablespace_name) a,
(select f.tablespace_name,
sum(f.bytes) bytes_free
from dba_free_space f
group by tablespace_name) b
where a.tablespace_name = b.tablespace_name;
验证是否有错误
dbv file=/oracle/oradata/new_tbs.dbf blocksize=8192;
查看服务器使用情况
select wait_class,total_waits,time_waited from v$system_wait_class order by time_waited;
快照保留时间设为2周,生成时间设为20分钟
execute dbms_workload_repository.modify_snapshot_settings(retention=>20160,interval=>20);
查看恢复的时间
select recovery_estimated_ios ios, actual_redo_blks redo,target_mttr, estimated_mttr, writes_mttr from v$instance_recovery;
查看Sql缓存的Sql语句
select sql_id from v$sql where sql_text='select max(c1) from t1';
查看表空间的大小,以及是否设置为自动增加
select file_id,file_name,bytes,autoextensible,increment_by,maxbytes from dba_data_files;
alter database datafile 7 autoextend on;
alter database datafile '/oradata/users01.dbf' autoextend on next 10m maxsize 200m;
查看表空间的空闲空间
select tablespace_name, sum(bytes) from dba_free_space group by tablespace_name;
select object_name, reason from dba_outstanding_alerts;
设置挂起的超时时间
alter session enable resumable timeout 60 name 'AR archive';
alter session enable resumable;
查看表占用空间量
select owner,bytes from dba_segments where segment_name='TEST';
alter table test enable row movement;
alter table test shrink space;
查看和压缩索引空间
ANALYZE TABLE table_name VALIDATE STRUCTURE CASCADE;
ANALYZE INDEX index_name VALIDATE STRUCTURE;
analyze index i1 validate structure;
select lf_rows_len, del_lf_rows_len from index_stats where name='I1';
select bytes from dba_segments where segment_name='I1';
alter index i1 shrink space;
analyze index i1 validate structure;
alter index i1 coalesce;
alter index i1 rebuild online;
alter index i1 rebuild online tablespace idx_ts;
重新创建control file
alter database backup controlfile to trace;
alter database backup controlfile to '/oracle/app/product/10.2.0/db_1/tmp';
show parameter user_dump_dest;
shutdown immediate;
startup nomount;
CREATE CONTROLFILE REUSE DATABASE "orcl" NORESETLOGS ARCHIVELOG
MAXLOGFILES 16 MAXLOGMEMBERS 3 MAXDATAFILES 100 MAXINSTANCES 8 MAXLOGHISTORY 454
LOGFILE
GROUP 1 (
'E:\oracle\product\10.1.0\oradata\orcl\REDO01.LOG'
) SIZE 10M,
GROUP 2 (
'E:\oracle\product\10.1.0\oradata\orcl\REDO02.LOG'
) SIZE 10M,
GROUP 3 (
'E:\oracle\product\10.1.0\oradata\orcl\REDO03.LOG'
) SIZE 10M
-- STANDBY LOGFILE
DATAFILE
'E:\oracle\product\10.1.0\oradata\orcl\SYSTEM01.DBF',
'E:\oracle\product\10.1.0\oradata\orcl\UNDOTBS01.DBF',
'E:\oracle\product\10.1.0\oradata\orcl\SYSAUX01.DBF',
'E:\oracle\product\10.1.0\oradata\orcl\USERS01.DBF',
'E:\oracle\product\10.1.0\oradata\orcl\EXAMPLE01.DBF'
CHARACTER SET WE8MSWIN1252
;
重建logfile
select group#,sequence#,archived,status from v$log;
select group#,status,member from v$logfile order by group#;
alter database clear logfile group 2;
alter database clear unarchived logfile group 2;
recover database until cancel;
查看恢复文件
select * from v$recovery_file_dest;
select reason from dba_outstanding_alerts;
修改redo log
alter system switch logfile;
select group#,sequence#,members,status from v$log;
select group#,status,member from v$logfile;
alter system checkpoint;
ALTER DATABASE ADD LOGFILE MEMBER 'E:\ORACLE\PRODUCT\10.1.0\ORADATA\ORCL\myAddLog' TO GROUP 1
显示当前连接用户
SHOW USER ;
在Oracle服务器上通过SQLPLUS查看本机IP地址
select sys_context('userenv','ip_address') from dual;
查看最大会话数
SELECT * FROM V$PARAMETER WHERE NAME LIKE 'proc%';
查看系统被锁的事务时间
select * from v$locked_object ;
查得数据库的SID
select name from v$database;
快速清空一个大表
truncate table table_name;
将表移动表空间
ALTER TABLE TABLE_NAME MOVE TABLESPACE_NAME;
将索引移动表空间
ALTER INDEX INDEX_NAME REBUILD TABLESPACE TABLESPACE_NAME
解锁
ALTER SYSTEM KILL SESSION ‘SID,SERIR#';
ORACLE产生随机函数
DBMS_RANDOM.RANDOM
查询当前用户对象
SELECT * FROM USER_OBJECTS;
SELECT * FROM DBA_SEGMENTS;
获取错误信息
SELECT * FROM USER_ERRORS;
获取链接状况
SELECT * FROM DBA_DB_LINKS;
查看数据库字符状况
SELECT * FROM NLS_DATABASE_PARAMETERS;
SELECT * FROM V$NLS_PARAMETERS;
select name,value$ from props$ where name like 'NLS%'
查询表空间信息
SELECT * FROM DBA_DATA_FILES;
查看各个表空间占用磁盘情况
select b.file_id 文件ID号, b.tablespace_name 表空间名, b.bytes 字节数, (b.bytes-sum(nvl(a.bytes,0))) 已使用, sum(nvl(a.bytes,0)) 剩余空间, sum(nvl(a.bytes,0))/(b.bytes)*100 剩余百分比 from dba_free_space a,dba_data_files b where a.file_id=b.file_id group by b.tablespace_name,b.file_id,b.bytes order by b.file_id
在ORACLE中取毫秒
select systimestamp from dual;
在字符串里加回车
select 'Welcome to visit'||chr(10)||'www.CSDN.NET' from dual ;
修改oracel数据库的默认日期
alter session set nls_date_format='yyyymmddhh24miss';
知道数据裤中某个表所在的tablespace
select tablespace_name from user_tables where table_name='TEST';
快速做一个和原表一样的备份表
create table New_table as (select * from Old_table);
看到数据库有多少个tablespace
select * from dba_tablespaces;
把“&”放入一条记录中
insert into table_name values (translate ('at{&}t','at{}','at'));
查有多少个数据库实例
SELECT * FROM V$INSTANCE;
查询数据库有多少表
select * from all_tables;
测试SQL语句执行所用的时间
set timing on ;
select * from tablename;
进行数字和Ascii码的转换
SELECT CHAR(65) FROM DUAL;
SELECT ASCII('A') FROM DUAL;
查询某天的数据
select * from table_name where trunc(日期字段)=to_date('2003-05-02','yyyy-mm-dd');
知道机器上的Oracle支持多少并发用户数
conn internal ;
show parameter processes ;
在给现有的日期加上2年
select add_months(sysdate,24) from dual;
返回大于等于N的最小整数值
SELECT CEIL(N) FROM DUAL;
返回小于等于N的最小整数值
SELECT FLOOR(N) FROM DUAL;
返回当前月的最后一天
SELECT LAST_DAY(SYSDATE) FROM DUAL
进行两个结果集互减
SELECT * FROM BSEMPMS_OLD MINUS SELECT * FROM BSEMPMS_NEW;
日期的各部分的常用的的写法
SELECT TO_CHAR(SYSDATE,'YYYY') FROM DUAL; -- 年
SELECT TO_CHAR(SYSDATE,'MM') FROM DUAL; -- 月
SELECT TO_CHAR(SYSDATE,'DD') FROM DUAL; -- 日
SELECT TO_CHAR(SYSDATE,'HH24') FROM DUAL; -- 时
SELECT TO_CHAR(SYSDATE,'MI') FROM DUAL; -- 分
SELECT TO_CHAR(SYSDATE,'SS') FROM DUAL; -- 秒
SELECT TO_CHAR(SYSDATE,'D') FROM DUAL; -- 星期
SELECT TO_CHAR(SYSDATE,'DDD') FROM DUAL; -- 第几天
SELECT TO_CHAR(SYSDATE,'WW') FROM DUAL; -- 第几周
SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') FROM DUAL; -- 时间
to_char(1210.78, '9999.9') = '1210.8'
to_char(1210.73, '9999.9') = '1210.7'
to_char(1210.73, '9, 999.99') = '1, 210.73'
to_char(1210.73, '$9, 999.00') = '$1, 210.73'
to_char(21, '000099') = '000021'
to_char(sysdate, 'ss') 取当前时间秒部分 a
to_char(sysdate, 'mi') 取当前时间分钟部分
to_char(sysdate, 'HH24') 取当前时间秒小时部分
to_char(sysdate, 'DD') 取当前时间日期部分
to_char(sysdate, 'MM') 取当前时间月部分
to_char(sysdate, 'YYYY') 取当前时间年部分
to_char(sysdate, 'w') 取当前时间是一个月中的第几周(从1日开始算)
to_char(sysdate, 'ww') 取当前时间是一年中的第几周(从1.1开始算)
to_char(sysdate, 'iw') 取当前时间是一年中的第几周(按实际日历的)
to_char(sysdate, 'd') 取当前时间是一周的第几天,从星期天开始,周六结束
to_char(sysdate, 'day') 取当前日是星期几,和数据库设置的字符集有关,会输出'Tuesday'
to_char(sysdate, 'ddd') 当前日是一年中的第几天
to_char(sysdate, 'yyyy/mm/dd');
to_char(sysdate, 'Month DD, YYYY');
to_char(sysdate, 'FMMonth DD, YYYY');
to_char(sysdate, 'MON DDth, YYYY');
to_char(sysdate, 'FMMON DDth, YYYY');
to_char(sysdate, 'FMMon ddth, YYYY');
转换为日期
SELECT TRUNC(SYSDATE) FROM DUAL;
SELECT TO_DATE('2003/08/01') FROM DUAL;
进行编码转换
SELECT CONVERT('要改变的字符串','US7ASCII','WE8HP') 'CONVERSION' FROM PUBS;
锁定某个账户
ALTER USER hr ACCOUNT LOCK;
ALTER USER hr ACCOUNT UNLOCK;
使用块变化追踪
alter database enable block change tracking using file
'e:/oracle/backup/change_tracking.dbf';
设置警告文件大小
alter system set max_dump_file_size='5m';
列出所有指标值
select internal_metric_name from v$alert_types where internal_metric_name like '%_ps';
列出未处理的警告
select reason,object_type type,object_name name from dba_outstanding_alerts;
select reason,object_type type,object_name name from dba_alert_history where object_name='SMALL';
设置表空间的临界区大小(50%,75%)
execute dbms_server_alert.set_threshold(-
metrics_id=>dbms_server_alert.tablespace_pct_full,-
warning_operator=>dbms_server_alert.operator_ge,-
warning_value=>'50',-
critical_operator=>dbms_server_alert.operator_ge,-
critical_value=>'75',-
observation_period=>1,consecutive_occurrences=>2,-
instance_name=>null,-
object_type=>dbms_server_alert.object_type_tablespace,-
object_name=>'SMALL');
循环插入数据
begin
for n in 1..500 loop
insert into toobig values('a row');
end loop;
commit;
end;
/
追踪客户端的SQL语句
alter system set sql_trace=true;
select s.username,s.sid,p.spid from v$session s, v$process p where s.paddr=p.addr;
alter session set sql_trace=true;
execute dbms_monitor.session_trace_disable( -
session_id=>162,serial_num=>14);
alter session set sql_trace=false;
替换受损的临时文件
alter tablespace temp_ts3 add tempfile 'c:/ts2.bdf' size 100m;
alter database tempfile 'c:/ts1.bdf' offline;
alter database tempfile 'c:/ts1.bdf' drop;
替换受损的表空间
create temporary tablespace temp_ts4 tempfile 'c:/ts4.bdf' size 100m;
alter database default temporary tablespace temp_ts4;
drop tablespace temp_ts3 including contents and datafiles;
查询联机日志
select group#,sequence#,bytes,members,archived,status from v$log;
select group#,status,member from v$logfile order by group#;
替换受损的联机日志
alter database drop logfile member 'c:/redo01.log';
alter database add logfile member 'c:/redo02.log' to group 1;
alter database clear logfile group 2;
发现索引文件错误
select name,status from v$datafile where file#=7;
select online_status,error from v$recover_file where file#=7;
监视索引有否被使用
alter index reg_id_pk monitoring usage;
select index_name, table_name,used from v$object_usage;
alter index reg_id_pk nomoinitoring usage;
外部文件表
CREATE DIRECTORY TEST AS 'e:\data\';
GRANT READ ON DIRECTORY TEST TO mydbuser;
GRANT WRITE ON DIRECTORY TEST TO mydbuser;
CREATE TABLE oldempx (empno number,empname char(20))
ORGANIZATION EXTERNAL
(TYPE ORACLE_LOADER DEFAULT DIRECTORY TEST ACCESS PARAMETERS
(RECORDS DELIMITED BY NEWLINE FIELDS TERMINATED BY ','
(empno char, empname char)) LOCATION ('emp1.txt'))
parallel 5 reject limit 200;
查看表结构
desc employees;
用命令行创建数据库
1.指定实例名
export ORACLE_SID=ax
cd $ORACLE_HOME/dbs
2.创建密码文件
orapwd file=orapwclone password=oracle
3.从原数据库拷贝spfile
create pfile from spfile;
4.创建物理文件
mkdir -p ax/(adump,bdump,cdump,udump)
mkdir /u01/app/oracle/oradata/ax
cp initorcl.ora initclone.ora
vi initclone.ora orcl -> ax
*.db_file_name_convert='/u01/app/oracle/oradata/orcl','/u01/app/oracle/oradata/ax'
*.log_file_name_convert='/u01/app/oracle/oradata/orcl','/u01/app/oracle/oradata/ax'
create spfile from pfile;
ROLLUP
如果是ROLLUP(A, B, C)的话,首先会对(A、B、C)进行GROUP BY,然后对(A、B)进行GROUP BY,然后是(A)进行GROUP BY,最后对全表进行GROUP BY操作。如果是GROUP BY CUBE(A, B, C),则首先会对(A、B、C)进行GROUP BY,然后依次是(A、B),(A、C),(A),(B、C),(B),(C),最后对全表进行GROUP BY操作。
create table emp_rollup as select * from dba_indexes;
select index_type, status, count(*) from emp_rollup group by index_type, status;
select index_type, status, count(*) from emp_rollup group by rollup(index_type, status);
select index_type, status, count(*) from emp_rollup group by cube(index_type, status);
timezone
SELECT DBTIMEZONE,SESSIONTIMEZONE FROM DUAL;
CREATE TABLE TIMESTAMP_TEST(TIME DATE, TIMESTP TIMESTAMP(3), TIMESTP_TZ TIMESTAMP(3) WITH TIME ZONE, TIMESTP_LTZ TIMESTAMP(3) WITH LOCAL TIME ZONE);
INSERT INTO TIMESTAMP_TEST VALUES(SYSDATE,SYSDATE,SYSDATE,SYSDATE);
SELECT * FROM TIMESTAMP_TEST;
ALTER SESSION SET TIME_ZONE='+10:00';
SELECT * FROM TIMESTAMP_TEST;
创建任务
DECLARE
task_name varchar2(30);
sql_stmt clob;
BEGIN
sql_stmt := 'select /*+ full(a) use_hash(a) ' ||
' parallel(a,8) full(b) use_hash(b) parallel(b,8) ' ||
' */ a.type, sum(a.amt_paid) ' ||
' from large_table a, large_table2 b ' ||
' where a.key = b.key ' ||
' and state_id = :bnd';
task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK(
sql_text => sql_stmt,
bind_list => sql_binds (anydata.ConvertNumber(32));
user_name => 'BUTERTB',
scope => 'COMPREHENSIVE',
time_limit => 45,
task_name => 'large_table_task',
description => 'Tune state totals query');
dbms_output.put_line('Task ' || task_name ||
' has been created.');
END;
/
执行任务
BEGIN
DBMS_SQLTUNE.EXECUTE_TUNING_TASK( task_name => 'large_table_task');
END;
The status of the executing task can be monitored by querying the DBA_ADVISOR_LOG view or V$SESSION_LONGOPS:
select status from dba_advisor_log where task_name = 'large_table_task';
BEGIN
DBMS_SQLTUNE.INTERRUPT_TUNING_TASK( task_name => 'large_table_task');
END;
If you want to interrupt a tuning task that is currently executing, use the INTERRUPT_
TUNING_TASK procedure:
BEGIN
DBMS_SQLTUNE.INTERRUPT_TUNING_TASK( task_name => 'large_table_task');
END;
Task Results
set long 1000
set longchunksize 1000
set linesize 132
select dbms_sqltune.report_tuning_task('large_table_task') from dual;
管理SQL_Profile
Accepting a SQL Profile
DECLARE
sqlprofile_name varchar2(30);
BEGIN
sqlprofile_name := DBMS_SQLTUNE.ACCEPT_SQL_PROFILE(
task_name => 'large_table_task',
profile_name => 'large_table_profile');
END;
改变SQL PROFILE
begin
DBMS_SQLTUNE.ALTER_SQL_PROFILE(
name => 'large_table_profile',
Atribute_name =>'STATUS',
Value => 'ENABLES');
END;
丢弃SQL PROFILE
BEGIN
DBMS_SQLTUNE.DROP_SQL_PROFILE(
Name => 'large_table_profile');
END;
管理SQL调整集
创建SQL调整集
BEGIN
DBMS_SQLTUNE.CREATE_SQLSET(
Sqlset_name => 'load_proc_set',
Description => 'SQL used in load procedure');
END;
加载SQL调整集
DECLARE
sql_cursor DBMS_SQLTUNE.SQLSET_CURSOR;
begin_snap number := 1; /* beginning snapshot id
end_snap number := 5; /* end snapshot id */
BEGIN
open sql_cursor for
select value(p)
from table (DBMS_SQLTUNE.SELECT_WORKLOAD_REPOSITORY(begin_snap, end_snap) p;
DBMS_SQLTUNE.LOAD_SQLSET(
sqlset_name => 'load_proc_set',
populate_cursor => sql_cursor);
END;
/
SQL Loader工具
○ sqlldr scott/tiger control=loader.ctl
○ loader.ctl 如下:
load data
infile 'c:\data\mydata.csv'
into table emp
fields terminated by "," optionally enclosed by '"'
(empno, empname, sal, deptno )
○ mydata.csv 如下:
10001,"Scott Tiger", 1000, 40
10002,"Frank Naude", 500, 20
创建Program
BEGIN
DBMS_SCHEDULER.CREATE_PROGRAM(
program_name => 'CALC_STATS2',
program_action => 'HR.UPDATE_HR_SCHEMA_STATS',
program_type => 'STORED_PROCEDURE',
enabled => TRUE);
END;
/
创建Schedules
BEGIN
DBMS_SCHEDULER.CREATE_SCHEDULE(
schedule_name => 'stats_schedule',
start_date => SYSTIMESTAMP,
end_date => SYSTIMESTAMP + 30,
repeat_interval =>
'FREQ=HOURLY;INTERVAL=1',
comments => 'Every hour');
END;
/
创建Time-base Job
BEGIN
DBMS_SCHEDULER.CREATE_JOB(
job_name=>'HR.DO_BACKUP',
job_type => 'EXECUTABLE',
job_action => '/home/usr/dba/rman/nightly_incr.sh',
start_date=> SYSDATE,
repeat_interval=>'FREQ=DAILY;BYHOUR=23',
/* next night at 11:00 PM */
comments => 'Nightly incremental backups');
END;
/
创建Event-base Job
BEGIN
DBMS_SCHEDULER.CREATE_JOB(
job_name=>'ADMIN.PERFORM_DATA_LOAD',
job_type => 'EXECUTABLE',
job_action => '/home/usr/dba/rman/report_failure.sh',
start_date => SYSTIMESTAMP,
event_condition => 'tab.user_data.object_owner =
''HR'' and tab.user_data.object_name = ''DATA.TXT''
and tab.user_data.event_type = ''FILE_ARRIVAL''
and tab.user_data.event_timestamp < 9 ',
queue_spec => 'HR.LOAD_JOB_EVENT_Q');
END;
执行JOB
DBMS_SCHEDULER.SET_ATTRIBUTE('hr.do_backup', 'raise_events', DBMS_SCHEDULER.JOB_FAILED);
查询JOB
SELECT job_name, status, error#, run_duration FROM USER_SCHEDULER_JOB_RUN_DETAILS;
Disk Group
1.创建
CREATE DISKGROUP dgroupA NORMAL REDUNDANCY
FAILGROUP controller1 DISK
'/devices/A1' NAME diskA1 SIZE 120G FORCE,
'/devices/A2',
'/devices/A3'
FAILGROUP controller2 DISK
'/devices/B1',
'/devices/B2',
'/devices/B3';
2.删除
DROP DISKGROUP dgroupA INCLUDING CONTENTS;
3.修改
ALTER DISKGROUP dgroupA ADD DISK
'/dev/rdsk/c0t4d0s2' NAME A5,
'/dev/rdsk/c0t5d0s2' NAME A6,
'/dev/rdsk/c0t6d0s2' NAME A7,
'/dev/rdsk/c0t7d0s2' NAME A8;
ALTER DISKGROUP dgroupA ADD DISK '/devices/A*';
ALTER DISKGROUP dgroupA DROP DISK A5;