oracle总结

阅读更多
oracle 总结:

1. 用于查看客户端ip
   select sys_context('userenv', 'ip_address') from dual;

2. 获取系统guid
select sys_guid() from dual;

3. 查看锁表
select * from v$locked_object;
select * from user_objects u where u.object_id='80025';

4. 删除触发器语句

-- Created on 2012-7-23 by LKF47688
declare
-- Local variables here
i integer;
v_sql varchar2(256);
begin
-- Test statements here
for item in (select * from dba_triggers d where d.table_name like 'DC%') loop

v_sql:='drop trigger '||item.trigger_name;
dbms_output.put_line(v_sql||';');
execute immediate v_sql;
end loop;
end;

5. 获取当前用户下oracle相关信息

select userenv('sessionid') from dual;
select userenv('entryid') from dual;
select userenv('language') from dual;
select userenv('terminal') from dual;
select * from v$session;
select sys_context('userenv','os_user') from dual;
select   SYS_CONTEXT('userenv', 'TERMINAL') terminal,
         SYS_CONTEXT('USERENV', 'LANGUAGE') language,
         SYS_CONTEXT('USERENV', 'SESSIONID') sessionid,
         SYS_CONTEXT('USERENV', 'INSTANCE') instance,
         SYS_CONTEXT('USERENV', 'ENTRYID') entryid,
         SYS_CONTEXT('USERENV', 'ISDBA') isdba,
         SYS_CONTEXT('USERENV', 'NLS_TERRITORY') nls_territory,
         SYS_CONTEXT('USERENV', 'NLS_CURRENCY') nls_currency,
         SYS_CONTEXT('USERENV', 'NLS_CALENDAR') nls_calendar,
         SYS_CONTEXT('USERENV', 'NLS_DATE_FORMAT') nls_date_format,
         SYS_CONTEXT('USERENV', 'NLS_DATE_LANGUAGE') nls_date_language,
         SYS_CONTEXT('USERENV', 'NLS_SORT') nls_sort,
         SYS_CONTEXT('USERENV', 'CURRENT_USER') current_user,
         SYS_CONTEXT('USERENV', 'CURRENT_USERID') current_userid,
         SYS_CONTEXT('USERENV', 'SESSION_USER') session_user,
         SYS_CONTEXT('USERENV', 'SESSION_USERID') session_userid,
         SYS_CONTEXT('USERENV', 'PROXY_USER') proxy_user,
         SYS_CONTEXT('USERENV', 'PROXY_USERID') proxy_userid,
         SYS_CONTEXT('USERENV', 'DB_DOMAIN') db_domain,
         SYS_CONTEXT('USERENV', 'DB_NAME') db_name,
         SYS_CONTEXT('USERENV', 'HOST') host,
         SYS_CONTEXT('USERENV', 'OS_USER') os_user,
         SYS_CONTEXT('USERENV', 'EXTERNAL_NAME') external_name,
         SYS_CONTEXT('USERENV', 'IP_ADDRESS') ip_address,
         SYS_CONTEXT('USERENV', 'NETWORK_PROTOCOL') network_protocol,
         SYS_CONTEXT('USERENV', 'BG_JOB_ID') bg_job_id,
         SYS_CONTEXT('USERENV', 'FG_JOB_ID') fg_job_id,
         SYS_CONTEXT('USERENV', 'AUTHENTICATION_TYPE') authentication_type,
         SYS_CONTEXT('USERENV', 'AUTHENTICATION_DATA') authentication_data
  from dual;

6. 获取服务端ip
   select utl_inaddr.get_host_address from dual;

7.查看主外键试图
select * from user_constraints;
select * from user_indexes;

8.查询表空间大小
SELECT a.tablespace_name 表空间,
total 表空间大小,
free 表空间剩余大小,
(total - free) 表空间使用大小,
round((total - free) / total, 4) * 100 使用率
FROM (SELECT tablespace_name, SUM(bytes) free
FROM dba_free_space
GROUP BY tablespace_name) a,
(SELECT tablespace_name, SUM(bytes) total
FROM dba_data_files
GROUP BY tablespace_name) b
WHERE a.tablespace_name = b.tablespace_name;

9.查询临时表空间大小
SELECT a.tablespace_name 表空间名,
total 表空间大小,
total - used 表空间剩余大小,
used 表空间使用大小,
round(used / total, 4) * 100 使用率
FROM (SELECT tablespace_name, SUM(bytes_used) used
FROM v$temp_space_header
GROUP BY tablespace_name) a,
(SELECT tablespace_name, SUM(bytes) total
FROM dba_temp_files
GROUP BY tablespace_name) b
WHERE a.tablespace_name = b.tablespace_name;

10.oracle 闪回表
drop方法:
select * from dc_t_cms_1;
drop table dc_t_cms_1;
flashback table dc_t_cms_1 to before drop;
delete方法:
select * from dc_t_cms_2;
delete dc_t_cms_2;
insert into dc_t_cms_2 select * from dc_t_cms_2 as of timestamp sysdate - 5/1440;

11.创建DBlink
create database link sysdblink connect to sysdb identified by sys_db1 using 'ip/sid';

sysdblink:是dblink名称,如果已经存在请重新命名
sysdb:是mdsp数据库sysdb的用户名,请根据实际情况填写。
sys_db1:是mdsp数据库sysdb的密码,请根据实际情况填写。
userdb:是mdsp数据库userdb的用户名,请根据实际情况填写。
user_db1:是mdsp数据库userdb的密码,请根据实际情况填写。
Ip:是mdsp数据库的ip地址。
Sid:是mdsp数据库的sid。

12. 触发器:
create or replace procedure dp_drop_trigger
as
v_sql varchar2(256);
begin
-- Test statements here
for item in (select * from user_triggers d where d.table_name like 'DC_TBL%') loop

v_sql:='drop trigger '||item.trigger_name;
dbms_output.put_line(v_sql||';');
execute immediate v_sql;
end loop;
end;

13.至关联关系失效

ALTER TABLE table_name DISABLE  CONSTRAINT_NAME;
如:

alter table DBTABLE_DICT disable constraints SYS_C0025714;
alter table DBTABLE_DICT enable constraints SYS_C0025714



14.查找列名
select c.COLUMN_NAME from user_tab_columns c where c.table_name=upper('T_CMP_TYPE_ARTIST');\


15、创建用户、表空间

//创建临时表空间  

create temporary tablespace user_temp  
tempfile 'D:\oracle\oradata\Oracle9i\user_temp.dbf' 
size 50m  
autoextend on  
next 50m maxsize 20480m  
extent management local;  

//创建数据表空间  
create tablespace test_data  
logging  
datafile 'D:\oracle\oradata\Oracle9i\user_data.dbf' 
size 50m  
autoextend on  
next 50m maxsize 20480m  
extent management local;  

//创建用户并指定表空间  
create user username identified by password  
default tablespace user_data  
temporary tablespace user_temp;  

//给用户授予权限  

grant connect,resource to username;

添加临时表空间
alter tablespace TEMP add tempfile '/opt/oracle/oracle/oradata/mdspdb/temp03.dbf' size 1000M; 

16、查看用户数据大小和表数据大小语句

select owner||'|'||sum(BYTES)||'|' from dba_segments where owner=upper('sysdb22') group by owner;
select t.table_name||'|'||t.num_rows||'|' from dba_all_tables t where t.owner=upper('$dbname') order by t.num_rows desc;

select owner,table_name,NUM_ROWS,BLOCKS*8/1024 "Size M",EMPTY_BLOCKS,LAST_ANALYZED
from dba_tables
where table_name=upper('t_cms_region');

17、查询用户进程
select b.spid from v$session a,v$process b where a.paddr=b.addr and a.username='ZCH';

18、写文件
create or replace procedure xp_WriteFile is
    fno utl_file.file_type;
  begin
    for file_recode in (select distinct(fileName) as fileName from L_CPSPInfoSync)

      loop
        fno := utl_file.fopen('PRM', file_recode.fileName, 'w');
        for filecontent_recode in (select fileContent
                                     from L_CPSPInfoSync
                                    where fileName = file_recode.filename)
            loop
                utl_file.put_line(fno, filecontent_recode.fileContent);
            end loop;

            utl_file.fclose(fno);
      end loop;
  end;
/
exec xp_WriteFile();
drop procedure xp_WriteFile;

19、创建dblink
create public database link link_iptv connect to sysdbiptv identified by sysdbiptv using 'IPTV';
DROP PUBLIC DATABASE LINK link_iptv;


20、oracle移动相关文件
--- 移动表空间文件
1、查询表空间的文件名称
SQL> select d.name from v$datafile d join v$tablespace t using(ts#) where name ='XPORT';
2、关闭数据库
SQL> shutdown immediate;
3、转移数据文件
SQL> ! mv /u04/oradata/xport.dbf /u06/oradata;
4、启动数据库
SQL> startup mount;
5、改变控制文件中的路径引用名称,指向新的路径
SQL> alter database rename file '/u04/oradata/xport.dbf' to '/u06/oradata/xport.dbf';
6、打开数据库
SQL> alter database open;
7、建立更新过的控制文件备份副本
SQL> alter database backup controlfile to trace;

-- 移动联机日志
1、查询联机日志
SQL> select group#,member from v$logfile order by group#,member;
2、关闭数据库
SQL> shutdown immediate;
3、移动文件
SQL> ! mv /u01/app/oracle/oradata/redo0[1-3].log /u04/data
SQL> startup mount
4、rename
SQL> alter database rename file '/u01/app/oracle/oradata/redo01.log' to '/u04/data/redo01.log';
SQL> alter database rename file '/u01/app/oracle/oradata/redo02.log' to '/u04/data/redo02.log';
SQL> alter database rename file '/u01/app/oracle/oradata/redo03.log' to '/u04/data/redo03.log';
5、打开数据库
SQL> alter databse open;

-- 移动控制文件
SQL> select name,value from v$spparameter where name='control_files';
SQL> show parameter control_files;
SQL> alter system set control_files = '/u02/oradata/control01.ctl', '/u03/oradata/control02.ctl', '/u04/oradata/control03.ctl' scope = spfile;
SQL> shutdown immediate;
SQL> ! mv /u01/app/oracle/oradata/control01.ctl /u02/oradata;
SQL> ! mv /u01/app/oracle/oradata/control02.ctl /u03/oradata;
SQL> ! mv /u01/app/oracle/oradata/control03.ctl /u04/oradata;
SQL> startup;
SQL> select name, value from v$spparameter where name = 'control_files';

19、表开并行
开并行
alter table mdsp_bosscustinfo parallel 6 add timezoneid number(10) default 0;
关并行
alter table mdsp_bosscustinfo noparallel;
查看并行力度
select table_name ,degree from dba_tables where table_name = 'MDSP_BOSSCUSTINFO';

20、alter table 对大表的处理
    昨天晚上在使用ideploy升级的时候升级脚本里对mdsp_bosscustinfo进行了添加字段的处理,
而我们环境上mdsp_bosscustinfo有2千多万的记录导致在alter的时候耗时很长时间
他们升级脚本里的处理方法是:
alter table mdsp_bosscustinfo add timezoneid number(10) default 0;
我修改后的处理方法是:
alter table mdsp_bosscustinfo parallel 6 add timezoneid number(10) default 0;
alter table mdsp_bosscustinfo noparallel;
后来咨询了下,大神给的方法是这样处理:
alter table table_name add ( col1 number(2) default 0 not null, col2 varchar2(30) default '000000' not null );

失效两列
Alter table mdsp_basetab set unused(useridentityinstnum,subscriberinstnum);


21、将密码有效期由默认的180天修改成“无限制”:

sql>ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

22、批量更新
--批量更新
declare
    type tntbl_array is table of rowid;
    vntbl_array tntbl_array;
cursor cur_source is
select rowid
from table_source
where ...;
    i_arraysize integer := 100;

begin

    open cur_source;

    loop

        fetch cur_source
         bulk collect
         into vntbl_array
        limit i_arraysize;

        forall i in 1..vntbl_array.count
        update table_source
           set col1 = 0,
                col2 = '000000'
        where rowid = vntbl_array(i);

--2万条提交一次
        if ( mod(cur_source%rowcount, 20000) = 0) then
            commit;
        end if;  

        exit when cur_source%notfound;  

    end loop;

    commit;

    if ( cur_source%isopen ) then
        close cur_source;
    end if;

exception
    when others then
        rollback;
        if ( cur_source%isopen ) then
            close cur_source;
        end if;
end;
/

23、oracle 行转列
create table table1  
(  
  id integer,  
  name varchar2(10)  
) ;

create table table2  
(  
  id integer,  
  role varchar2(10)  
) ;

insert into table1 (id, name) values (1, '张三');  
insert into table1 (id, name) values (2, '李四');  
commit;  

insert into table2 (id, role) values (1, '查询');  
insert into table2 (id, role) values (1, '分析');  
insert into table2 (id, role) values (1, '决策');  
insert into table2 (id, role) values (2, '查询');  


select table1.*, wmsys.wm_concat(role)
  from table1, table2
where table1.id = table2.id
group by table1.id, table1.name;

结果:



23、insert +append
总结得出以下3点结论:
a、非归档模式下,只需append就能大量减少redo的产生;归档模式下,只有append+nologging才能大量减少redo。
b、insert /*+ append */ 时会对表加锁(排它锁),会阻塞表上的除了select以外所有DML语句;传统的DML在TM enqueue上使用模式3(row exclusive),其允许其他DML在相同的模式上获得TM enqueue。但是直接路径加载在TM enqueue使用模式6(exclusive),这使其他DML在直接路径加载期间将被阻塞。
c、insert /*+ append */ 直接路径加载,速度比常规加载方式快。因为是从HWM的位置开始插入,也许会造成空间浪费。

24、查询锁表语句

SELECT l.session_id sid,
       s.serial#,
       l.locked_mode,
       l.oracle_username,
       l.os_user_name,
       s.machine,
       s.terminal,
       o.object_name,
       s.logon_time
  FROM v$locked_object l, all_objects o, v$session s
WHERE l.object_id = o.object_id
   AND l.session_id = s.sid
ORDER BY sid, s.serial#;

25、执行计划查看方法:

SQL> explain plan for select * from ts_productorder t,mdsp_basetab m where t.subscriberkey = m.subscriberkey;

Explained

SQL> select * from table(dbms_xplan.display);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
Plan hash value: 2306354100
--------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 39 | 8853 | 118
| 1 | NESTED LOOPS | | | |
| 2 | NESTED LOOPS | | 39 | 8853 | 118
| 3 | TABLE ACCESS FULL | TS_PRODUCTORDER | 38 | 3724 | 4
|* 4 | INDEX RANGE SCAN | PK_BASETAB | 1 | | 2
| 5 | TABLE ACCESS BY INDEX ROWID| MDSP_BASETAB | 1 | 129 | 3
--------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
   4 - access("T"."SUBSCRIBERKEY"="M"."SUBSCRIBERKEY")

17 rows selected


26、 获取时区方法
select to_number(substr(tz_offset(sessiontimezone), 1, 3)) from dual;


27、存储过程自定义异常

create or replace procedure dc_prc_replace_categorycode(oldcatecode in varchar2,newcatecode in varchar2)
authid current_user is
v_date varchar(24) default '[' || to_char(sysdate,'yyyy-MM-DD HH24:mi:ss') || '] ';
v_sql_error_code pls_integer;
v_sql_error_message varchar2(512);
v_num int default 0;
ex_notfount exception;
PRAGMA EXCEPTION_INIT(ex_notfount, -20001);
begin
select count(1) into v_num from t_cmp_type_mediacategory t where t.categorycode=''||newcatecode||'';
if (v_num > 0) then
raise_application_error
(-20001,'[WARN] [dc_prc_replace_categorycode] the category code '|| oldcatecode || ' exists!');
else
execute immediate 'update mdsp_t_categoryinfo set externalid='''||newcatecode||''' where externalid='''||oldcatecode||''''; ----externalid
execute immediate 'update t_cmp_type_mediacategory set categorycode='''||newcatecode||''' where categorycode='''||oldcatecode||''''; -----categorycode
execute immediate 'update mdsp_t_priceinfoml set serviceid='''||newcatecode||''' where serviceid='''||oldcatecode||''''; -----serviceid
commit;
end if;

exception
when ex_notfount then
raise_application_error
(-20001,'[WARN] [dc_prc_replace_categorycode] the category code '|| oldcatecode || ' exists!');
return;
end dc_prc_replace_categorycode;
/

28、设置触发器限制ip登录
CREATE OR REPLACE TRIGGER disablelogin_sysdb2
     AFTER logon ON sysdb2.schema
DECLARE
    ipaddr VARCHAR2(30);
BEGIN
    SELECT sys_context('userenv', 'ip_address') INTO ipaddr FROM dual;
    IF ipaddr not in ('10.137.73.155','10.137.226.79','10.135.178.74') THEN
            raise_application_error('-20001', 'You can not login,Please contact administrator');
    END IF;
END disablelogin_sysdb2;

29. ctas 开并行另一种方式
create table dc_tbl_user_migration_bad tablespace CBS_LOG_DAT parallel (degree 2) nologging as
    select * from dc_tbl_user_migration_all d where d.errorresult is not null

30、查看信息
select p.sofar,p.TOTALWORK,p.SID,p.TIME_REMAINING from v$session_longops p where p.sid = 1355;

31、表分析语句

SQL> create or replace procedure DC_P_GRTHER_STAT as
  2 begin
  3 dbms_stats.gather_table_stats(ownname => 'USERDB99',
  4 tabname => 'NUMSERVICE',
  5 estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,
  6 degree => 4,
  7 cascade => true,
  8 method_opt => 'FOR ALL COLUMNS SIZE 1',
  9 granularity => 'all');
10 end;
11 
12 /

Procedure created

SQL> exec userdb99.DC_P_GRTHER_STAT;

32、分析用户
exec dbms_stats.gather_schema_stats(ownname=> 'USERDB99',estimate_percent => dbms_stats.auto_sample_size,degree=> 2);

分析表:
exec dbms_stats.gather_table_stats(ownname=>'USERDB1',tabname=>'DC_TBL_SUBSCRIPTION_ALL',estimate_percent => dbms_stats.AUTO_SAMPLE_SIZE);

33、替换换行sql
select substr(trim(TRANSLATE (name_lang1, CHR (13) || CHR (10), ',')),1,1),c.name_lang1 from t_cmp_type_artist c where c.firstletter is null;

34、oracle 转换格林威治时间和转换带毫秒
create or replace function dc_fun_oracle_to_unix(in_date DATE) return number is
begin
return( (in_date -TO_DATE('19700101','yyyymmdd'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone),1,3))*3600);
end;

select to_char(systimestamp, 'yyyymmddhh24missff3') from dual;

你可能感兴趣的:(oracle总结)