首页 > 代码库 > Oracle常用命令

Oracle常用命令

Oracle常用命令

一.  日志管理

      1. 强制日志切换

    sql> alter system switch logfile;

   2. 强制检查点

    sql> alter system checkpoint;

   3. 添加日志组

    sql> alter database add logfile [group 4]

    sql> (‘/disk3/log4a.rdo‘,‘/disk4/log4b.rdo‘) size 1m;

   4. 添加联机重做日志成员

    sql> alter database add logfile member

    sql> ‘/disk3/log1b.rdo‘ to group 1,

    sql> ‘/disk4/log2b.rdo‘ to group 2;

   5. 改变联机重做日志成员名

    sql> alter database rename file ‘c:/oracle/oradata/oradb/redo01.log‘

    sql> to ‘c:/oracle/oradata/redo01.log‘;

   6. 删除联机重做日志组

    sql> alter database drop logfile group 3;

   7. 删除联机重做日志成员

    sql> alter database drop logfile member ‘c:/oracle/oradata/redo01.log‘;

   8. 清除联机重做日志文件

    sql> alter database clear [unarchived] logfile ‘c:/oracle/log2a.rdo‘;

   9. 用logminer分析重做日志文件

    a.  in the init.ora specify utl_file_dir = ‘ ‘

    b.  sql> execute dbms_logmnr_d.build(‘oradb.ora‘,‘c:oracleoradblog‘);

    c.  sql> execute dbms_logmnr_add_logfile(‘c:oracleoradataoradbredo01.log‘,

     sql> dbms_logmnr.new);

    d.  sql> execute dbms_logmnr.add_logfile(‘c:oracleoradataoradbredo02.log‘,

     sql> dbms_logmnr.addfile);

    e.  sql> execute  dbms_logmnr.start_logmnr(dictfilename=>  ‘c:oracleoradblogoradb.ora‘);

    f.  sql> select * from v$logmnr_contents(v$logmnr_dictionary,v$logmnr_parameters

     sql> v$logmnr_logs);

    g.  sql> execute dbms_logmnr.end_logmnr;
 


二.  表空间管理

         1. 创建表空间

    sql> create tablespace tablespace_name datafile ‘c:oracleoradatafile1.dbf‘ size 100m,

    sql> ‘c:oracleoradatafile2.dbf‘ size 100m minimum extent 550k [logging/nologging]

    sql> default storage (initial 500k next 500k maxextents 500 pctinccease 0)

    sql> [online/offline] [permanent/temporary] [extent_management_clause]

   2. 创建本地管理的表空间

    sql> create tablespace user_data datafile ‘c:oracleoradatauser_data01.dbf‘

    sql> size 500m extent management local uniform. size 10m;

   3. 创建临时表空间

    sql> create temporary tablespace temp tempfile ‘c:oracleoradatatemp01.dbf‘

    sql> size 500m extent management local uniform. size 10m;

   4. 改变表空间存储设置

    sql> alter tablespace app_data minimum extent 2m;

    sql> alter tablespace app_data default storage(initial 2m next 2m maxextents 999);

   5. 使表空间脱机/联机

    sql> alter tablespace app_data offline;

    sql> alter tablespace app_data online;

   6. 使表空间只读/可写

    sql> alter tablespace app_data read only|write;

   7. 删除表空间

    sql> drop tablespace app_data including contents;

   8. 使数据文件自动扩展

    sql> alter tablespace app_data add datafile ‘c:oracleoradataapp_data01.dbf‘ size 200m

    sql> autoextend on next 10m maxsize 500m;

   9. 手动改变数据文件大小

    sql> alter database datafile ‘c:oracleoradataapp_data.dbf‘ resize 200m;

   10. 移动数据文件

    sql> alter tablespace app_data rename datafile ‘c:oracleoradataapp_data.dbf‘

    sql> to ‘c:oracleapp_data.dbf‘;

   11. 删除数据文件

    sql> alter database rename file ‘c:oracleoradataapp_data.dbf‘

    sql> to ‘c:oracleapp_data.dbf‘;


三.  表

          1. 创建表

    sql> create table table_name (column datatype,column datatype]....)

    sql> tablespace tablespace_name [pctfree integer] [pctused integer]

    sql> [initrans integer] [maxtrans integer]

    sql> storage(initial 200k next 200k pctincrease 0 maxextents 50)

    sql> [logging|nologging] [cache|nocache]

   2. 根据已存在的表创建新表

    sql> create table table_name [logging|nologging] as subquery

   3. 创建临时表

    sql> create global temporary table xay_temp as select * from xay;

    on commit preserve rows/on commit delete rows

   4. pctfree、pctused设置计算方法

            pctfree = (average row size - initial row size) *100 /average row size

    pctused = 100-pctfree- (average row size*100/available data space)

   5. 改变存储块初始大小

    sql> alter table table_name pctfree=30 pctused=50 storage(next 500k

    sql> minextents 2 maxextents 100);

   6. 手动分配数据块

    sql> alter table table_name allocate extent(size 500k datafile  ‘c:/oracle/data.dbf‘);

   7. 移动表空间

    sql> alter table employee move tablespace users;

   8. 回收不用的表空间

    sql> alter table table_name deallocate unused [keep integer]

   9. 截断表

    sql> truncate table table_name;

   10. 删除表

    sql> drop table table_name [cascade constraints];

   11. 删除列

    sql> alter table table_name drop column comments cascade constraints checkpoint 1000;

    alter table table_name drop columns continue;

   12. 把列标记为无用

    sql> alter table table_name set unused column comments cascade constraints;

    alter table table_name drop unused columns checkpoint 1000;

    alter table orders drop columns continue checkpoint 1000

    data_dictionary : dba_unused_col_tabs

           13. 建一个和a表结构一样的空表
 
            SQL> create table b as select * from a where 1=2;
            SQL> create table b(b1,b2,b3) as select a1,a2,a3 from a where 1=2;
   
           14. 查看现有回滚段及其状态

           SQL> col segment format a30
           SQL> SELECT    SEGMENT_NAME,OWNER,TABLESPACE_NAME,SEGMENT_ID,FILE_ID,STATUS   FROM  DBA_ROLLBACK_SEGS;


四.  索引

         1. 创建基于函数的索引

    sql> create index summit.item_quantity on summit.item(quantity-quantity_shipped);

   2. 创建B-tree索引

    sql> create [unique] index index_name on table_name(column,.. asc/desc) tablespace

    sql> tablespace_name [pctfree integer] [initrans integer] [maxtrans integer]

    sql> [logging | nologging] [nosort] storage(initial 200k next 200k pctincrease 0

    sql> maxextents 50);

   3. 设置index pctfree值

           pctfree(index)=(maximum number of rows-initial number of  rows)*100/maximum number of rows

   4. 创建反转键索引

    sql> create unique index xay_id on xay(a) reverse pctfree 30 storage(initial 200k

    sql> next 200k pctincrease 0 maxextents 50) tablespace indx;

   5. 创建位图索引

    sql> create bitmap index xay_id on xay(a) pctfree 30 storage( initial 200k next  200k

    sql> pctincrease 0 maxextents 50) tablespace indx;

   6. 改变索引的存储参数

    sql> alter index xay_id storage (next 400k maxextents 100);

   7. 分配/回收索引空间

    sql> alter index xay_id allocate extent(size 200k datafile ‘c:/oracle/index.dbf‘);

    alter index xay_id deallocate unused;


五.  约束

          1. 定义约束为immediate/deferred

    sql> alter session set constraint[s] = immediate/deferred/default;

    set constraint[s] constraint_name/all immediate/deferred;

   2.  删除表的时候同时删除约束
 
           sql> drop table table_name cascade constraints

    sql> drop tablespace tablespace_name including contents cascade constraints

   3.  建表的时候创建约束

    sql> create table xay(id number(7) constraint xay_id primary key deferrable

    sql> using index storage(initial 100k next 100k) tablespace indx);

    primary key/unique/references table(column)/check

   4. 使约束失效

    sql> alter table xay enable novalidate constraint xay_id;

   5. 使约束有效

    sql> alter table xay enable validate constraint xay_id;


六.  LOAD数据

          1. 以insert方式插入数据

    sql> insert /*+append */ into emp nologging

    sql> select * from emp_old;

   2. 以parallel方式直接插入数据

    sql> alter session enable parallel dml;

    sql> insert /*+parallel(emp,2) */ into emp nologging

    sql> select * from emp_old;

   3. 用sql*loader导入

    sql> sqlldr scott/tiger

    sql> control = ulcase6.ctl

    sql> log = ulcase6.log direct=true


七.  数据整理

         1. 用export导出

    $exp scott/tiger tables(dept,emp) file=c:emp.dmp log=exp.log  compress=n direct=y

   2. 用import导入

    $imp scott/tiger tables(dept,emp) file=emp.dmp log=imp.log ignore=y

   3. 移动表空间

    sql>alter tablespace sales_ts read only;

    $exp sys/.. file=xay.dmp transport_tablespace=y tablespace=sales_ts

    triggers=n constraints=n

    $copy datafile

    $imp sys/.. file=xay.dmp transport_tablespace=y datafiles=(/disk1/sles01.dbf,/disk2

    /sles02.dbf)

    sql> alter tablespace sales_ts read write;

   4. transport设置

    sql> DBMS_tts.transport_set_check(ts_list =>‘sales_ts‘ ..,incl_constraints=>true);

    在表transport_set_violations 中查看

          sql> dbms_tts.isselfcontained 为true 是, 表示自包含


八.  密码安全与资源管理

          1. 控制帐户锁及密码

    sql> alter user juncky identified by oracle account unlock;

   2. 创建密码设置的profile文件

    sql> create profile grace_5 limit failed_login_attempts 3

    sql> password_lock_time unlimited password_life_time 30

    sql>password_reuse_time 30 password_verify_function verify_function

    sql> password_grace_time 5;

   3. 更改profile文件

    sql> alter profile default failed_login_attempts 3

    sql> password_life_time 60 password_grace_time 10;

   4. 删除profile文件

    sql> drop profile grace_5 [cascade];

   5. 创建资源限制的profile文件

    sql> create profile developer_prof limit sessions_per_user 2

    sql> cpu_per_session 10000 idle_time 60 connect_time 480;

   6.  允许资源限制

    sql> alter system set resource_limit=true;


九.  用户管理

          1. 创建一个用户

    sql> create user juncky identified by oracle default tablespace users

    sql> temporary tablespace temp quota 10m on data password expire

    sql> [account lock|unlock] [profile profilename|default];

   2. 改变用户的表空间配额

    sql> alter user juncky quota 0 on users;

   3. 删除一个用户

    sql> drop user juncky [cascade];

   4.  监控用户

    view: dba_users , dba_ts_quotas

         5. 查看数据库库对象
 
          select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status;
   
         6. 查看当前所有对象

           select * from tab;

          7. 显示当前连接用户
 
            show user

         8. 通过授权的方式来创建用户

            grant connect,resource to test identified by test;

        9. 用户间复制数据

           copy from user1 to user2 create table2 using select * from table1;


十.  特权管理

         1. 查看系统权限 => system_privilege_map ,dba_sys_privs,session_privs

   2. 赋权

    sql> grant create session,create table to managers;

    sql> grant create session to scott with admin option;

    with admin option can grant or revoke privilege from any user or role;

   3. sysdba and sysoper权限

    sysoper: startup,shutdown,alter database open|mount,alter database  backup controlfile,

    alter tablespace begin/end backup,recover database

    alter database archivelog,restricted session

    sysdba: sysoper privileges with admin option,create database,recover database until

   4. password file members查看=> v$pwfile_users

   5. 文件访问权限设置

       O7_dictionary_accessibility =true restriction access to view or tables in other schema

   6. revoke系统权限

       sql> revoke create session from scott;

   7. 赋对象权限

    sql> grant execute on dbms_pipe to public;

    sql> grant update(first_name,salary) on employee to karen with grant  option;

   8. 查看对象权限 => dba_tab_privs, dba_col_privs

   9. revoke对象权限

    sql> revoke execute on dbms_pipe from scott [cascade constraints];

   10. 查看审计记录=> sys.aud$

   11.  保护审计跟踪表

    sql> audit delete on sys.aud$ by access;

   12. statement审计

    sql> audit user;

   13. privilege审计

    sql> audit select any table by summit by access;

   14. schema object 审计

    sql> audit lock on summit.employee by access whenever successful;

   15. 查看审计选项=> all_def_audit_opts,dba_stmt_audit_opts, dba_priv_audit_opts,dba_obj_audit_opts

   16. 查看审计结果=> dba_audit_trail,dba_audit_exists,dba_audit_object,  dba_audit_session,dba_audit_statement


十一.  规则管理器

          1. 创建roles

    sql> create role sales_clerk;

    sql> create role hr_clerk identified by bonus;

    sql> create role hr_manager identified externally;

   2. 修改role

    sql> alter role sales_clerk identified by commission;

    sql> alter role hr_clerk identified externally;

    sql> alter role hr_manager not identified;

   3. 分配roles

    sql> grant sales_clerk to scott;

    sql> grant hr_clerk to hr_manager;

    sql> grant hr_manager to scott with admin option;

   4. 创建默认role

    sql> alter user scott default role hr_clerk,sales_clerk;

    sql> alter user scott default role all;

    sql> alter user scott default role all except hr_clerk;

    sql> alter user scott default role none;

   5. enable and disable roles

    sql> set role hr_clerk;

    sql> set role sales_clerk identified by commission;

    sql> set role all except sales_clerk;

    sql> set role none;

   6. remove role from user

    sql> revoke sales_clerk from scott;

    sql> revoke hr_manager from public;

   7. remove role

    sql> drop role hr_manager;

   8. display role information

    view: =>dba_roles,dba_role_privs,role_role_privs,  dba_sys_privs,role_sys_privs,role_tab_privs,session_roles


十二.  备份与恢复

         1.  与备份恢复有关的动态性能视图

           v$sga,v$instance,v$process,v$bgprocess,v$database,v$datafile,v$sgastat

   2.  Rman需要设置的参数

          Rman need set dbwr_IO_slaves or backup_tape_IO_slaves and large_pool_size

   3.  监控Parallel Rollback

    > v$fast_start_servers , v$fast_start_transactions

   4. 数据库冷备(noarchivelog)

    > shutdown immediate

    > cp files /backup/

    > startup

   5. 恢复数据文件到不同位置

    > connect system/manager as sysdba

    > startup mount

    > alter database rename file ‘/disk1/../user.dbf‘ to ‘/disk2/../user.dbf‘;

    > alter database open;

   6. 恢复有关的语法

         --recover a mounted database

    >recover database;

    >recover datafile ‘/disk1/data/df2.dbf‘;

    >alter database recover database;

    --recover an opened database

    >recover tablespace user_data;

    >recover datafile 2;

    >alter database recover datafile 2;

   7. 自动应用redo log文件

    >set autorecovery on

    >recover automatic datafile 4;

   8. 完全恢复语法

    --method 1(mounted databae)

    >copy c:backupuser.dbf c:oradatauser.dbf

    >startup mount

    >recover datafile ‘c:oradatauser.dbf;

    >alter database open;

    --method 2(opened database,initially opened,not system or rollback  datafile)

    >copy c:backupuser.dbf c:oradatauser.dbf (alter tablespace offline)

    >recover datafile ‘c:oradatauser.dbf‘ or

    >recover tablespace user_data;

    >alter database datafile ‘c:oradatauser.dbf‘ online or

    >alter tablespace user_data online;

    --method 3(opened database,initially closed not system or rollback datafile)

    >startup mount

    >alter database datafile ‘c:oradatauser.dbf‘ offline;

    >alter database open

    >copy c:backupuser.dbf d:oradatauser.dbf

    >alter database rename file ‘c:oradatauser.dbf‘ to ‘d:oradatauser.dbf‘

    >recover datafile ‘e:oradatauser.dbf‘ or recover tablespace user_data;

    >alter tablespace user_data online;

    --method 4(loss of data file with no backup and have all archive log)

    >alter tablespace user_data offline immediate;

    >alter database create datafile ‘d:oradatauser.dbf‘ as ‘c:oradatauser.dbf‘‘

    >recover tablespace user_data;

    >alter tablespace user_data online

   9. 联机备份

    > alter tablespace user_data begin backup;

    > copy files /backup/

    > alter database datafile ‘/c:/../data.dbf‘ end backup;

    > alter system switch logfile;

   10. 备份控制文件

    > alter database backup controlfile to ‘control1.bkp‘;

    > alter database backup controlfile to trace;

   11. 恢复(noarchivelog mode)

    > shutdown abort

    > cp files

    > startup

   12. 结束备份模式

    >alter database datafile 2 end backup;

   13. 清除redo log文件

    >alter database clear unarchived logfile group 1;

    >alter database clear unarchived logfile group 1 unrecoverable datafile;

   14. redo log恢复

    >alter database add logfile group 3 ‘c:oradataredo03.log‘ size 1000k;

    >alter database drop logfile group 1;

    >alter database open;

    or >cp c:oradataredo02.log‘ c:oradataredo01.log

    >alter database clear logfile ‘c:oradatalog01.log‘;

        15. 查看表空间的名称及大小

         select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size
           from dba_tablespaces t, dba_data_files d
          where t.tablespace_name = d.tablespace_name
          group by t.tablespace_name;

         16.   查看表空间物理文件的名称及大小

           select tablespace_name, file_id, file_name,
           round(bytes/(1024*1024),0) total_space
           from dba_data_files
           order by tablespace_name;

        17.  查看回滚段名称及大小
 
           select segment_name, tablespace_name, r.status,
           (initial_extent/1024) InitialExtent,(next_extent/1024) NextExtent,
          max_extents, v.curext CurExtent
          From dba_rollback_segs r, v$rollstat v
          Where r.segment_id = v.usn(+)
          order by segment_name ;
   
        18.  查看控制文件
 
          select name from v$controlfile;

         19.   查看日志文件

            select member from v$logfile;

           20.   查看表空间的使用情况

  select sum(bytes)/(1024*1024) as free_space,tablespace_name
    from dba_free_space
    group by tablespace_name;

    SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED, C.BYTES  FREE,
   (B.BYTES*100)/A.BYTES "% USED",(C.BYTES*100)/A.BYTES "% FREE"
    FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_USED B,SYS.SM$TS_FREE C
    WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND  A.TABLESPACE_NAME=C.TABLESPACE_NAME;

          21. 查看数据文件放置的路径

           SQL> col file_name format a50
           SQL> select tablespace_name,file_id,bytes/1024/1024,file_name   from dba_data_files order by file_id;

          22. 查看数据库的创建日期和归档方式

            Select Created, Log_Mode, Log_Mode From V$Database;

 

十三.  其它

           1. 查询oracle server端的字符集
 
            SQL>select userenv(‘language‘) from dual;

            2. 查看数据库的版本
   
           Select version FROM Product_component_version   Where SUBSTR(PRODUCT,1,6)=‘Oracle‘;

           select * from v$version;

            select * from product_component_version;

           3. 把SQL*Plus当计算器
 
            select 100*20 from dual;   
 
            4. 连接字符串

                SQL> select 列1||列2 from 表1;
                SQL> select concat(列1,列2) from 表1;   

            5. 查询当前日期

              select to_char(sysdate,‘yyyy-mm-dd,hh24:mi:ss‘) from dual;
    
           6. 视图中不能使用order by,但可用group by代替来达到排序目的

              create view a as select b1,b2 from b group by b1,b2;