<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>惜分飞 &#187; Oracle 开发</title>
	<atom:link href="https://www.xifenfei.com/category/database/oracle/oracle_dev/feed" rel="self" type="application/rss+xml" />
	<link>https://www.xifenfei.com</link>
	<description>提供7*24专业数据库(Oracle,SQL Server,MySQL,PostgreSQL等)恢复和技术支持@Tel:17813235971</description>
	<lastBuildDate>Sat, 07 Nov 2026 15:45:44 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>DBMS_SESSION.set_context提示ORA-01031问题解决</title>
		<link>https://www.xifenfei.com/2024/08/dbms_session-set_context-ora-01031.html</link>
		<comments>https://www.xifenfei.com/2024/08/dbms_session-set_context-ora-01031.html#comments</comments>
		<pubDate>Sat, 24 Aug 2024 12:53:05 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>
		<category><![CDATA[DBMS_SESSION ORA-01031]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=10933</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2024/08/dbms_session-set_context-ora-01031.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2024/08/dbms_session-set_context-ora-01031.html" target="_blank">DBMS_SESSION.set_context提示ORA-01031问题解决</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>最近给客户把oracle数据库从11.2.0.3 aix平台迁移到19.23 linux平台,使用impdp+network_link 按照用户的方式处理,结果发现有一个程序运行异常<br />
<a href="https://www.xifenfei.com/wp-content/uploads/2024/08/ORA-01031.png"><img src="https://www.xifenfei.com/wp-content/uploads/2024/08/ORA-01031.png" alt="ORA-01031" width="439" height="242" class="alignnone size-full wp-image-10934" /></a><br />
<hr />
ORA-01031: insufficient privileges通过程序跟踪确认是在调用以下部分异常</p>
<pre class="brush: sql; title: ; notranslate">
 DBMS_SESSION.set_context (
         'back_exec',
         'back_exec_log_no',
         v_back_exec_log_no
……
</pre>
<p>通过跟踪执行用户权限,确认EXECUTE ON SYS.DBMS_SESSION已经授权.做一个简单测试重现给问题:</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; show user;
USER 为 &quot;SYS&quot;

SQL&gt; exec DBMS_SESSION.SET_CONTEXT('test_ctx', 'a', '1');
BEGIN DBMS_SESSION.SET_CONTEXT('test_ctx', 'a', '1'); END;

*
第 1 行出现错误:
ORA-01031: 权限不足
ORA-06512: 在 &quot;SYS.DBMS_SESSION&quot;, line 114
ORA-06512: 在 line 1

SQL&gt; GRANT EXECUTE ON SYS.DBMS_SESSION TO sys;

授权成功。

SQL&gt; exec DBMS_SESSION.SET_CONTEXT('test_ctx', 'a', '1');
BEGIN DBMS_SESSION.SET_CONTEXT('test_ctx', 'a', '1'); END;

*
第 1 行出现错误:
ORA-01031: 权限不足
ORA-06512: 在 &quot;SYS.DBMS_SESSION&quot;, line 114
ORA-06512: 在 line 1
</pre>
<p>基于这种情况,肯定不是权限问题,查询官方DBMS_SESSION.set_context部分描述<br />
<a href="https://www.xifenfei.com/wp-content/uploads/2024/08/dbms_session.set_context.png"><img src="https://www.xifenfei.com/wp-content/uploads/2024/08/dbms_session.set_context.png" alt="dbms_session.set_context" width="1239" height="760" class="alignnone size-full wp-image-10935" /></a><br />
<hr />
确认namespace:The namespace of the application context to be set, limited to 128 bytes. Exceeding the maximum permissible length will result in an error during the execution of the procedure.</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create context test_ctx using sys.DBMS_SESSION;

上下文已创建。

SQL&gt; exec DBMS_SESSION.SET_CONTEXT('test_ctx', 'a', '1');

PL/SQL 过程已成功完成。

</pre>
<p>官方有相关的执行例子:<a href="https://docs.oracle.com/en/database/oracle/oracle-database/19/dbseg/using-application-contexts-to-retrieve-user-information.html#GUID-BF276A5E-BC14-4B49-A02A-2EC984325805" title="&quot;Example: Creating a Global Application Context that Uses a Client Session ID&quot;" rel="noopener" target="_blank">Example: Creating a Global Application Context that Uses a Client Session ID</a></p>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/11/plsql%e7%9a%84%e5%ae%9a%e4%b9%89%e8%80%85%e4%b8%8e%e8%b0%83%e7%94%a8%e8%80%85.html" rel="bookmark" class="crp_title">pl/sql的定义者与调用者</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2023/04/update-user-ora-01031.html" rel="bookmark" class="crp_title">update user$报ORA-01031错误</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/07/sqlplus-errordetails.html" rel="bookmark" class="crp_title">Oracle23ai新特性&#8212;sqlplus errordetails功能</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/05/distributed-storage-ora-00354-ora-00353.html" rel="bookmark" class="crp_title">分布式存储故障导致数据库无法启动故障处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/05/ora-00600-16515.html" rel="bookmark" class="crp_title">收集统计信息报ORA-00600 16515问题解决</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/08/ora-01031-insufficient-privileges.html" rel="bookmark" class="crp_title">ORA-01031: insufficient privileges</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/02/hudsonlcock-li-mkp-recovery.html" rel="bookmark" class="crp_title">.[hudsonL@cock.li].mkp勒索加密数据库完美恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/08/oracle%e4%b9%8b%e6%95%b0%e6%8d%ae%e5%ba%93%e5%85%a8%e7%90%83%e5%8c%96%e7%bc%96%e7%a0%81.html" rel="bookmark" class="crp_title">oracle之数据库全球化(编码)</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2026/01/hgdb-rm-rf-recovery.html" rel="bookmark" class="crp_title">记录一次国产数据库被rm -rf /*删除的救援过程</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/08/ora-600-kcvfdb_pdb_set_clean_scn-cleanckpt.html" rel="bookmark" class="crp_title">ORA-600 [kcvfdb_pdb_set_clean_scn: cleanckpt] 相关bug</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2023/05/ora-600-16703-vandalism-ora-00704-ora-00922.html" rel="bookmark" class="crp_title">ORA-600 16703故障,客户找人恢复数据库,数据库被进一步恶意破坏&#8212;ORA-00704 ORA-00922</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/11/ora-600-kccpb_sanity_check_2.html" rel="bookmark" class="crp_title">ora-600 kccpb_sanity_check_2故障处理</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2024/08/dbms_session-set_context-ora-01031.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>触发器找出密码错误应用</title>
		<link>https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html</link>
		<comments>https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html#comments</comments>
		<pubDate>Wed, 01 Nov 2023 15:33:43 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>
		<category><![CDATA[触发器 密码错误]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=10481</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html" target="_blank">触发器找出密码错误应用</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>经常会遇到修改oracle业务用户密码之后,由于部分应用密码没有被正确修改(忘记修改,或者修改错误了),导致数据库被hang或者用户被锁的情况,对于这样的情况,通过一个logon触发器可以快速找到</p>
<pre class="brush: sql; title: ; notranslate">
create or replace trigger logon_denied_to_alert
after servererror on database
declare
 message   varchar2(120);
 IP        varchar2(15);
 v_os_user varchar2(80);
 v_module  varchar2(50);
 v_action  varchar2(50);
 v_pid     varchar2(10);
 v_sid     number;
 v_username  varchar2(50);
 v_suser      varchar2(50);
begin
 IF (ora_is_servererror(1017)) THEN
   if sys_context('userenv', 'network_protocol') = 'tcp' then
     IP := sys_context('userenv', 'ip_address');
   else
     select distinct sid into v_sid from sys.v_$mystat;
     SELECT p.SPID
       into v_pid
       FROM V$PROCESS p, V$SESSION v
      WHERE p.ADDR = v.PADDR
        AND v.sid = v_sid;
   end if;
   v_os_user := sys_context('userenv', 'os_user');
   v_username := sys_context('userenv', 'CURRENT_USER');
   v_suser := SYS_CONTEXT('USERENV','SESSION_USER');
   dbms_application_info.READ_MODULE(v_module, v_action);
   message := to_char(sysdate, 'Dy Mon dd HH24:MI:SS YYYY') ||
              ' logon denied from '||v_username||' '||v_suser||' '|| nvl(IP, v_pid) || ' ' || v_os_user ||
              ' with ' || v_module || ' ' || v_action;
   sys.dbms_system.ksdwrt(2, message);
 end if;
end;
/
</pre>
<p>测试</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create user test identified by oracle;

User created.

SQL&gt; grant dba to test;

Grant succeeded.
</pre>
<p>直接本地登录</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; conn test/test
ERROR:
ORA-01017: invalid username/password; logon denied


Warning: You are no longer connected to ORACLE.

---alert日志记录
Wed Nov 01 23:15:04 2023 logon denied from SYS  12886 oracle with sqlplus@iZbp1hx0enix3hix1kvyrxZ (TNS V1-V3) 
</pre>
<p>通过tns登录</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; conn  test/oracl1@172.27.54.81:1522/orcl
ERROR:
ORA-01017: invalid username/password; logon denied


Warning: You are no longer connected to ORACLE.

---alert日志报错
Wed Nov 01 23:31:51 2023 logon denied from SYS  172.27.54.81 oracle with sqlplus@iZbp1hx0enix3hix1kvyrxZ (TNS V1-V3) 
</pre>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html" rel="bookmark" class="crp_title">实现trigger集中记录所有库ddl操作</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2015/04/11g-%e4%bd%bf%e7%94%a8-alter-user-identified-by-values-password-%e6%81%a2%e5%a4%8d%e5%8e%86%e5%8f%b2%e5%af%86%e7%a0%81.html" rel="bookmark" class="crp_title">11g 使用 alter user  identified by values password 恢复历史密码</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2015/01/%e7%89%a9%e7%90%86%e5%a4%87%e5%ba%93%e5%9c%a8read-only%e6%97%b6%e6%8a%a5ora-01552%e9%94%99%e8%af%af%e5%a4%84%e7%90%86.html" rel="bookmark" class="crp_title">物理备库在read only时报ORA-01552错误处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/12/%e8%a7%a6%e5%8f%91%e5%99%a8%e8%ae%b0%e5%bd%95%e7%94%a8%e6%88%b7%e7%99%bb%e5%bd%95%e4%bf%a1%e6%81%af.html" rel="bookmark" class="crp_title">触发器记录用户登录信息</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2019/09/standby-modify-password-delay.html" rel="bookmark" class="crp_title">oracle active dataguard修改密码备库延迟生效</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/08/ora-01031-insufficient-privileges.html" rel="bookmark" class="crp_title">ORA-01031: insufficient privileges</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/11/plsql%e7%9a%84%e5%ae%9a%e4%b9%89%e8%80%85%e4%b8%8e%e8%b0%83%e7%94%a8%e8%80%85.html" rel="bookmark" class="crp_title">pl/sql的定义者与调用者</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/%e9%80%9a%e8%bf%87%e4%bf%ae%e6%94%b9%e5%9f%ba%e8%a1%a8link%e8%ae%a9%e9%9d%9epublic-dblink%e5%8f%98%e4%b8%bapublic.html" rel="bookmark" class="crp_title">通过修改基表(link$)让非public dblink变为public</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/05/password_rollover_time.html" rel="bookmark" class="crp_title">PASSWORD_ROLLOVER_TIME&#8212;实现新老密码短期共存</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/12/%e8%a7%a6%e5%8f%91%e5%99%a8%e5%ae%9e%e7%8e%b0%e6%8c%87%e5%ae%9a%e7%94%a8%e6%88%b7%e7%99%bb%e5%bd%95oracle.html" rel="bookmark" class="crp_title">触发器实现指定用户登录oracle</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/11/oracle-%e5%a4%96%e9%83%a8%e8%a1%a8.html" rel="bookmark" class="crp_title">ORACLE 外部表</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/05/%e5%85%b3%e4%ba%8eoracle-11g%e5%af%86%e7%a0%81%e5%a4%a7%e5%b0%8f%e5%86%99%e6%95%8f%e6%84%9f%e7%8c%9c%e6%83%b3user-spare4.html" rel="bookmark" class="crp_title">关于ORACLE 11G密码大小写敏感猜想(USER$.SPARE4)</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>plsql 插入blob</title>
		<link>https://www.xifenfei.com/2022/05/plsql-insert-blob.html</link>
		<comments>https://www.xifenfei.com/2022/05/plsql-insert-blob.html#comments</comments>
		<pubDate>Mon, 02 May 2022 08:45:40 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=9676</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2022/05/plsql-insert-blob.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2022/05/plsql-insert-blob.html" target="_blank">plsql 插入blob</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>plsql 插入blob</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create bigfile tablespace t_xifenfei datafile 'e:/oradata/orcl/t_blob.dbf' size 128M autoextend on;

表空间已创建。


SQL&gt; create table u0425.t_blob(a int, b varchar(10), c blob) tablespace t_xifenfei ;

表已创建。


SQL&gt; create or replace directory expdp_dir as 'e:/';

目录已创建。


SQL&gt; declare
  2  b_file bfile;
  3  b_lob blob;
  4  begin
  5  insert into u0425.t_blob(a,b,c) values(1,'xifenfei', empty_blob()) return c into b_lob;
  6  b_file:=bfilename('EXPDP_DIR','0430.DMP');
  7  dbms_lob.open(b_file,dbms_lob.file_readonly);
  8  dbms_lob.loadfromfile(b_lob,b_file,dbms_lob.getlength(b_file));
  9  dbms_lob.close(b_file);
 10  commit;
 11  end;
 12  /

PL/SQL 过程已成功完成。

SQL&gt; select * from u0425.t_blob where rownum&lt;2;

         A B
---------- ----------
C
--------------------------------------------------------------------------------
         1 xifenfei
0301914E3B98006780BC00019FC70146A1A3633DBC4B089DCF3DFCD951D559000000010000100003
6907E6041E0D3037000000020200000077D10000000000FA1A880022535953222E225359535F4558


SQL&gt; select a,b,dbms_lob.getlength(c) from u0425.t_blob where rownum&lt;2;

         A B          DBMS_LOB.GETLENGTH(C)
---------- ---------- ---------------------
         1 xifenfei               142024704
</pre>
<p>插入的blob字段和实际文件大小，内容一致,插入是成功的<br />
<a href="https://www.xifenfei.com/wp-content/uploads/2022/05/20220502164359.jpg"><img src="https://www.xifenfei.com/wp-content/uploads/2022/05/20220502164359.jpg" alt="20220502164359" width="480" height="172" class="alignnone size-full wp-image-9677" /></a><br />
<a href="https://www.xifenfei.com/wp-content/uploads/2022/05/20220502164727.jpg"><img src="https://www.xifenfei.com/wp-content/uploads/2022/05/20220502164727.jpg" alt="20220502164727" width="695" height="415" class="alignnone size-full wp-image-9680" /></a></p>
<hr />
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/02/%e5%9c%a8sqlplus%e4%b8%ad%e6%93%8d%e4%bd%9cblob%e5%92%8cclob.html" rel="bookmark" class="crp_title">在sqlplus中操作blob和clob</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html" rel="bookmark" class="crp_title">lob类型数据转换为系统文件</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/%e4%bf%ae%e6%94%b9clob%e5%ad%97%e6%ae%b5%e5%b9%b6%e6%8f%92%e5%85%a5%e6%96%b0%e8%a1%a8.html" rel="bookmark" class="crp_title">修改clob字段并插入新表</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/07/ora-702_recovery-tool.html" rel="bookmark" class="crp_title">ORA-00702一键恢复工具</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/07/delete-partition-oracle-recovery.html" rel="bookmark" class="crp_title">误删除分区oracle数据库恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/06/ora-01110-ora-17070-osd-04006.html" rel="bookmark" class="crp_title">ORA-01110 ORA-17070 OSD-04006 故障恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/12/crs-2674-root-sh-failed.html" rel="bookmark" class="crp_title">RAC节点时间间隔过大导致执行root.sh不成功</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/01/mallox-db-recovery.html" rel="bookmark" class="crp_title">.mallox加密数据库恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/07/makop-ora-recovery.html" rel="bookmark" class="crp_title">oracle文件勒索恢复工具&#8212;.makop病毒恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/02/decrypt20firemail-cc-eking.html" rel="bookmark" class="crp_title">.[decrypt20@firemail.cc].eking 数据库勒索恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/11/2022-11-oracle-btb-recovery.html" rel="bookmark" class="crp_title">最近两种加密oracle数据库文件勒索病毒可以实现直接open数据库恢复</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/04/win-fs-corruption-recovery.html" rel="bookmark" class="crp_title">win文件系统损坏oracle恢复</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2022/05/plsql-insert-blob.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ORACEL坏查询对象批量脚本</title>
		<link>https://www.xifenfei.com/2014/09/oracel%e5%9d%8f%e6%9f%a5%e8%af%a2%e5%af%b9%e8%b1%a1%e6%89%b9%e9%87%8f%e8%84%9a%e6%9c%ac.html</link>
		<comments>https://www.xifenfei.com/2014/09/oracel%e5%9d%8f%e6%9f%a5%e8%af%a2%e5%af%b9%e8%b1%a1%e6%89%b9%e9%87%8f%e8%84%9a%e6%9c%ac.html#comments</comments>
		<pubDate>Tue, 02 Sep 2014 08:54:28 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>
		<category><![CDATA[ORACLE坏块检查]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=5492</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2014/09/oracel%e5%9d%8f%e6%9f%a5%e8%af%a2%e5%af%b9%e8%b1%a1%e6%89%b9%e9%87%8f%e8%84%9a%e6%9c%ac.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2014/09/oracel%e5%9d%8f%e6%9f%a5%e8%af%a2%e5%af%b9%e8%b1%a1%e6%89%b9%e9%87%8f%e8%84%9a%e6%9c%ac.html" target="_blank">ORACEL坏查询对象批量脚本</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>查询坏块</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; set lines 120
SQL&gt; select * from v$database_block_corruption;

     FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO      
---------- ---------- ---------- ------------------ ---------      
         3      35418          1                  0 FRACTURED      
         3      61344          1                  0 FRACTURED      
         3      31065          1                  0 CORRUPT        
         3      36673          1                  0 CORRUPT        
         3      36721          1                  0 CORRUPT        
         3      42881          1                  0 CORRUPT        
         1      66738          1                  0 CORRUPT        
         3      36329          1                  0 CORRUPT        
         3      36617          1                  0 CORRUPT        
         3      32404          1                  0 FRACTURED      
         3      36281          1                  0 FRACTURED      

     FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO      
---------- ---------- ---------- ------------------ ---------      
         3      36625          1                  0 FRACTURED      
         1      39041          1                  0 CORRUPT        
         3      36713          1                  0 CORRUPT        
        10      69927          1                  0 FRACTURED      
        26      94244          1                  0 CORRUPT        

已选择16行。
</pre>
<p>查询坏块对应对象</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; set pagesize 2000
SQL&gt;          set linesize 250
SQL&gt;      SELECT e.owner, e.segment_type, e.segment_name, e.partition_name, c.file#
  2       , greatest(e.block_id, c.block#) corr_start_block#
  3       , least(e.block_id+e.blocks-1, c.block#+c.blocks-1) corr_end_block#
  4       , least(e.block_id+e.blocks-1, c.block#+c.blocks-1)
  5         - greatest(e.block_id, c.block#) + 1 blocks_corrupted
  6       , null description
  7    FROM dba_extents e, v$database_block_corruption c
  8   WHERE e.file_id = c.file#
  9     AND e.block_id &lt;= c.block# + c.blocks - 1
 10     AND e.block_id + e.blocks - 1 &gt;= c.block#
 11  UNION
 12  SELECT s.owner, s.segment_type, s.segment_name, s.partition_name, c.file#
 13       , header_block corr_start_block#
 14       , header_block corr_end_block#
 15       , 1 blocks_corrupted
 16       , 'Segment Header' description
 17    FROM dba_segments s, v$database_block_corruption c
 18   WHERE s.header_file = c.file#
 19     AND s.header_block between c.block# and c.block# + c.blocks - 1
 20  UNION
 21  SELECT null owner, null segment_type, null segment_name, null partition_name, c.file#
 22       , greatest(f.block_id, c.block#) corr_start_block#
 23       , least(f.block_id+f.blocks-1, c.block#+c.blocks-1) corr_end_block#
 24       , least(f.block_id+f.blocks-1, c.block#+c.blocks-1)
 25         - greatest(f.block_id, c.block#) + 1 blocks_corrupted
 26       , 'Free Block' description
 27    FROM dba_free_space f, v$database_block_corruption c
 28   WHERE f.file_id = c.file#
 29     AND f.block_id &lt;= c.block# + c.blocks - 1
 30     AND f.block_id + f.blocks - 1 &gt;= c.block#
 31  order by file#, corr_start_block#;

OWNER            SEGMENT_TYPE       SEGMENT_NAME                 PARTITION_NAME                      FILE# CORR_START_BLOCK# CORR_END_BLOCK# BLOCKS_CORRUPTED DESCRIPTION
---------------- ----------------- ----------------------- ------------------------------- ------ ----------------- --------------- ---------------- --------------      
SYS              TABLE              OBJ$                                                        1             39041           39041                1                     
                                                                                                1             66738           66738                1 Free Block          
SYSMAN           INDEX              MGMT_METRICS_1HOUR_PK                                       3             31065           31065                1                     
SYS              TABLE              WRH$_SQL_BIND_METADATA                                      3             32404           32404                1                     
SYS              TABLE              WRH$_BG_EVENT_SUMMARY                                       3             35418           35418                1                     
SYS              INDEX PARTITION    WRH$_FILESTATXS_PK      WRH$_FILEST_1232289473_41482        3             36281           36281                1                     
SYS              TABLE PARTITION    WRH$_SYSTEM_EVENT       WRH$_SYSTEM_1232289473_41482        3             36329           36329                1                     
SYS              TABLE PARTITION    WRH$_SGASTAT            WRH$_SGASTA_1232289473_41482        3             36617           36617                1                     
SYS              INDEX PARTITION    WRH$_SGASTAT_U          WRH$_SGASTA_1232289473_41482        3             36625           36625                1                     
SYS              INDEX PARTITION    WRH$_PARAMETER_PK       WRH$_PARAME_1232289473_41482        3             36673           36673                1                     
SYS              TABLE PARTITION    WRH$_SERVICE_STAT       WRH$_SERVIC_1232289473_41482        3             36713           36713                1                     
SYS              INDEX PARTITION    WRH$_SERVICE_STAT_PK    WRH$_SERVIC_1232289473_41482        3             36721           36721                1                     
SYS              TABLE PARTITION    WRH$_LATCH              WRH$_LATCH_1232289473_41482         3             42881           42881                1                     
SYS              TABLE              WRI$_ADV_ACTIONS                                            3             61344           61344                1                     
EXAM             TABLE              EXAM_ITEMS_OLD                                             10             69927           69927                1                     
CPR              TABLE              NEED_MONITOR                                               26             94244           94244                1                     
                                                                                                                                                                         
已选择16行。                                                                                                                                                             
                                                                                                                                                                         
SQL&gt;                                                                                                                                                                     
SQL&gt; spool off
</pre>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/%e8%ae%b0%e5%bd%95%e4%b8%80%e6%ac%a1ora-00600kdsgrp1%e5%88%86%e6%9e%90.html" rel="bookmark" class="crp_title">记录一次ORA-00600[kdsgrp1]分析</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/09/%e5%81%87%e5%9d%8f%e5%9d%97%e5%bc%95%e8%b5%b7%e6%81%90%e6%85%8c.html" rel="bookmark" class="crp_title">假坏块引起恐慌</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/04/segment-header-ora-1578.html" rel="bookmark" class="crp_title">segment header异常对象删除处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/07/read-by-other-session%e7%ad%89%e5%be%85%e4%ba%8b%e4%bb%b6.html" rel="bookmark" class="crp_title">Read by other session等待事件</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2024/06/os-error-os-23.html" rel="bookmark" class="crp_title">O/S-Error: (OS 23) 数据错误(循环冗余检查)&#8212;故障处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/02/table%e4%b8%ad%e5%90%84%e7%a7%8d%e5%9d%8f%e5%9d%97%e5%af%b9selectdml%e6%93%8d%e4%bd%9c%e5%bd%b1%e5%93%8d.html" rel="bookmark" class="crp_title">table中各种坏块对select/dml操作影响</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/07/%e6%95%b0%e6%8d%ae%e5%ba%93%e6%8a%a5ora-00607ora-006004194%e9%94%99%e8%af%af.html" rel="bookmark" class="crp_title">数据库报ORA-00607/ORA-00600[4194]错误</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/05/shell%e8%84%9a%e6%9c%ac%e8%8e%b7%e5%be%97extents%e5%88%86%e5%b8%83.html" rel="bookmark" class="crp_title">shell脚本获得extents分布</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/%e8%ae%b0%e5%bd%95%e4%b8%80%e6%ac%a1ora-60013013%e5%a4%84%e7%90%86%e8%bf%87%e7%a8%8b.html" rel="bookmark" class="crp_title">记录一次ORA-600[13013]处理过程</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/06/latch-cache-buffers-chains.html" rel="bookmark" class="crp_title">latch: cache buffers chains</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/08/oracle-recovery-tools-repair-free-corruption-block.html" rel="bookmark" class="crp_title">Oracle Recovery Tools修复空闲坏块</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/%e9%80%9a%e8%bf%87rowid%e6%89%be%e5%9b%9e%e5%9d%8f%e5%9d%97%e6%95%b0%e6%8d%ae.html" rel="bookmark" class="crp_title">通过ROWID找回坏块数据</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2014/09/oracel%e5%9d%8f%e6%9f%a5%e8%af%a2%e5%af%b9%e8%b1%a1%e6%89%b9%e9%87%8f%e8%84%9a%e6%9c%ac.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>实现trigger集中记录所有库ddl操作</title>
		<link>https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html</link>
		<comments>https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html#comments</comments>
		<pubDate>Wed, 20 Jun 2012 14:36:17 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=3380</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html" target="_blank">实现trigger集中记录所有库ddl操作</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>今天客户说了一个我感觉有意思的需求:在一个库上的一张表记录所有库的ddl操作,实现方式：在一个库上建立表和触发器,其他库上通过dblink+同义词+触发器实现ddl操作记录到远程的表中.他当时写了一个触发器,但是有错误,想让我协助解决.在我们的一起努力下,解决了该触发器在dblink同义词的库上出错的问题.我这里测试使用的是10g的库做为存储所有库的ddl记录的库,11g库做为一个通过dblink插入ddl操作记录的库.<br />
<strong>在10g数据库库中操作</strong><br />
1.创建记录ddl操作表</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; conn chf/xifenfei
Connected.
SQL&gt; create table t_ddl_audit(
  2  db_name varchar2(30),
  3  login_user varchar2(30),
  4  ddl_time date,
  5  ip_address varchar2(20),
  6  audsid varchar2(20),
  7  schema_user varchar2(30),
  8  schema_object varchar2(40),
  9  login_tool varchar2(40),
 10  os_user varchar2(40),
 11  ddl_sql varchar2(4000));

Table created.
</pre>
<p>2.创建触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create or replace trigger tri_ddl_audit
  2    before ddl on database
  3  declare
  4    n           number;
  5    str_stmt    varchar2(4000);
  6    sql_text    ora_name_list_t;
  7    l_trace     number;
  8    v_module    varchar2(50);
  9    v_action    varchar2(50);
 10    str_session v$session%rowtype;
 11  begin
 12    n := ora_sql_txt(sql_text);
 13    for i in 1 .. n loop
 14      str_stmt := substr(str_stmt || sql_text(i), 1, 3000);
 15    end loop;
 16    dbms_application_info.READ_MODULE(v_module, v_action);
 17    INSERT INTO chf.t_ddl_audit
 18      (db_name,
 19       login_user,
 20       ddl_time,
 21       ip_address,
 22       audsid,
 23       schema_user,
 24       schema_object,
 25       login_tool,
 26       os_user,
 27       ddl_sql)
 28    VALUES
 29      (sys_context('USERENV', 'db_name'),
 30       ora_login_user,
 31       SYSDATE,
 32       sys_context('USERENV', 'IP_ADDRESS'),
 33       userenv('SESSIONID'),
 34       ora_dict_obj_owner,
 35       ora_dict_obj_name,
 36       v_module,
 37       sys_context('userenv', 'os_user'),
 38       str_stmt);
 39  exception
 40    when no_data_found then
 41      null;
 42  end;
 43  /

Trigger created.
</pre>
<p>3.测试触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; conn chf/xifenfei
Connected.
SQL&gt; create table t_xff as select * from dba_tables where rownum=1;

Table created.

SQL&gt; select db_name,login_user,ddl_sql from t_ddl_audit;

DB_NAME                        LOGIN_USER
------------------------------ ------------------------------
DDL_SQL
-----------------------------------------------------------------
XFF                            CHF
create table t_xff as select * from dba_tables where rownum=1
</pre>
<p><strong>在11g数据库中操作</strong><br />
1.创建dblink和同义词</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create database link &quot;ora10g_dblink&quot;
  2   connect to chf
  3    identified by &quot;xifenfei&quot;
  4     using 'ora10g';

Database link created.

SQL&gt; create  synonym t_ddl_audit for t_ddl_audit@ora10g_dblink;

Synonym created.
</pre>
<p>2.第一次创建触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create or replace trigger tri_ddl_audit
  2    before ddl on database
  3  declare
  4    n           number;
  5    str_stmt    varchar2(4000);
  6    sql_text    ora_name_list_t;
  7    l_trace     number;
  8    v_module    varchar2(50);
  9    v_action    varchar2(50);
 10    str_session v$session%rowtype;
 11  begin
 12    n := ora_sql_txt(sql_text);
 13    for i in 1 .. n loop
 14      str_stmt := substr(str_stmt || sql_text(i), 1, 3000);
 15    end loop;
 16    dbms_application_info.READ_MODULE(v_module, v_action);
 17    INSERT INTO t_ddl_audit
 18      (db_name,
 19       login_user,
 20       ddl_time,
 21       ip_address,
 22       audsid,
 23       schema_user,
 24       schema_object,
 25       login_tool,
 26       os_user,
 27       ddl_sql)
 28    VALUES
 29      (sys_context('USERENV', 'db_name'),
 30       ora_login_user,
 31       SYSDATE,
 32       sys_context('USERENV', 'IP_ADDRESS'),
 33       userenv('SESSIONID'),
 34       ora_dict_obj_owner,
 35       ora_dict_obj_name,
 36       v_module,
 37       sys_context('userenv', 'os_user'),
 38       str_stmt);
 39  exception
 40    when no_data_found then
 41      null;
 42  end;
 43  /

Trigger created.
</pre>
<p>3.测试触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create table t_xff as select * from dba_objects where rownum&lt;10;
create table t_xff as select * from dba_objects where rownum&lt;10
                                    *
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-02070: database  does not support  in this context
ORA-06512: at line 15
</pre>
<p>出现ORA-02070错误,估计是类此sys_context(&#8216;userenv&#8217;, &#8216;os_user&#8217;)导致。<br />
<br />
4.第二次创建触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create or replace trigger tri_ddl_audit
  2    before ddl on database
  3  declare
  4    n           number;
  5    str_stmt    varchar2(4000);
  6    sql_text    ora_name_list_t;
  7    l_trace     number;
  8    v_module    varchar2(50);
  9    v_action    varchar2(50);
 10    v_db_name   varchar2(50);
 11    v_ip_addr   varchar2(50);
 12    v_os        varchar2(50);
 13    v_session_id varchar2(50);
 14    str_session v$session%rowtype;
 15  begin
 16    n := ora_sql_txt(sql_text);
 17    for i in 1 .. n loop
 18      str_stmt := substr(str_stmt || sql_text(i), 1, 3000);
 19    end loop;
 20    dbms_application_info.READ_MODULE(v_module, v_action);
 21    v_db_name :=sys_context('USERENV', 'db_name');
 22    v_ip_addr :=sys_context('USERENV', 'IP_ADDRESS');
 23    v_os:=sys_context('userenv', 'os_user');
 24    v_session_id:=userenv('SESSIONID');
 25    INSERT INTO t_ddl_audit
 26      (db_name,
 27       login_user,
 28       ddl_time,
 29       ip_address,
 30       audsid,
 31       schema_user,
 32       schema_object,
 33       login_tool,
 34       os_user,
 35       ddl_sql)
 36    VALUES
 37      (v_db_name,
 38       ora_login_user,
 39       SYSDATE,
 40       v_ip_addr,
 41      v_session_id,
 42       ora_dict_obj_owner,
 43       ora_dict_obj_name,
 44       v_module,
 45       v_os,
 46       str_stmt);
 47  exception
 48    when no_data_found then
 49      null;
 50  end;
 51  /

Trigger created.
</pre>
<p>5.继续测试触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; drop table t3;
drop table t3
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-02069: global_names parameter must be set to TRUE for this operation
ORA-06512: at line 23
</pre>
<p>根据ORA-02069,查询资料发现是通过dblink插入数据使用了变量和常量的方式混合使用导致该错误,修改触发器全部使用变量方式<br />
<br />
6.第三次创建触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create or replace trigger tri_ddl_audit
  2    before ddl on database
  3  declare
  4    n           number;
  5    str_stmt    varchar2(4000);
  6    sql_text    ora_name_list_t;
  7    l_trace     number;
  8    v_module    varchar2(50);
  9    v_action    varchar2(50);
 10    v_db_name   varchar2(50);
 11    v_ip_addr   varchar2(50);
 12    v_os        varchar2(50);
 13    v_session_id varchar2(50);
 14    v_loginuser    varchar2(50);
 15     v_obj_name varchar2(50);
 16    v_owner    varchar2(50);
 17    str_session v$session%rowtype;
 18  begin
 19    n := ora_sql_txt(sql_text);
 20    for i in 1 .. n loop
 21      str_stmt := substr(str_stmt || sql_text(i), 1, 3000);
 22    end loop;
 23    dbms_application_info.READ_MODULE(v_module, v_action);
 24    v_db_name :=sys_context('USERENV', 'db_name');
 25    v_ip_addr :=sys_context('USERENV', 'IP_ADDRESS');
 26    v_os:=sys_context('userenv', 'os_user');
 27    v_session_id:=userenv('SESSIONID');
 28    v_loginuser:= ora_login_user;
 29    v_owner:=ora_dict_obj_owner;
 30    v_obj_name:=ora_dict_obj_name;
 31    INSERT INTO t_ddl_audit
 32      (db_name,
 33       login_user,
 34       ddl_time,
 35       ip_address,
 36       audsid,
 37       schema_user,
 38       schema_object,
 39       login_tool,
 40       os_user,
 41       ddl_sql)
 42    VALUES
 43      (v_db_name,
 44       v_loginuser,
 45       SYSDATE,
 46       v_ip_addr,
 47      v_session_id,
 48       v_owner,
 49       v_obj_name,
 50       v_module,
 51       v_os,
 52       str_stmt);
 53  exception
 54    when no_data_found then
 55      null;
 56  end;   
 57  /

Trigger created.
</pre>
<p>7.测试触发器</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create table t_xff11 as select * from dba_tables where rownum&lt;10;

Table created.

SQL&gt; select db_name,login_user,ddl_sql from t_ddl_audit;

DB_NAME                        LOGIN_USER
------------------------------ ------------------------------
DDL_SQL
-----------------------------------------------------------------
ora11g                         CHF
create table t_xff11 as select * from dba_tables where rownum&lt;10

XFF                            CHF
create table t_xff as select * from dba_tables where rownum=1
</pre>
<p><strong>补充说明</strong><br />
这个方案个人感觉是一个实验室中的方案,在实际的生成环境中很难应用上<br />
1.trigger记录ddl操作本身效率不高<br />
2.如果某个库不能访问存储ddl操作的表的数据库,将导致该数据库所有ddl操作hang住,从而可能使得该数据库hang住的风险.</p>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2023/11/trigger-get-password-error-app.html" rel="bookmark" class="crp_title">触发器找出密码错误应用</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2015/01/%e7%89%a9%e7%90%86%e5%a4%87%e5%ba%93%e5%9c%a8read-only%e6%97%b6%e6%8a%a5ora-01552%e9%94%99%e8%af%af%e5%a4%84%e7%90%86.html" rel="bookmark" class="crp_title">物理备库在read only时报ORA-01552错误处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/12/%e8%a7%a6%e5%8f%91%e5%99%a8%e8%ae%b0%e5%bd%95%e7%94%a8%e6%88%b7%e7%99%bb%e5%bd%95%e4%bf%a1%e6%81%af.html" rel="bookmark" class="crp_title">触发器记录用户登录信息</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/12/%e8%a7%a6%e5%8f%91%e5%99%a8%e5%ae%9e%e7%8e%b0%e6%8c%87%e5%ae%9a%e7%94%a8%e6%88%b7%e7%99%bb%e5%bd%95oracle.html" rel="bookmark" class="crp_title">触发器实现指定用户登录oracle</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/02/table%e5%87%bd%e6%95%b0%e7%94%a8%e6%b3%95.html" rel="bookmark" class="crp_title">table()函数用法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/11/plsql%e7%9a%84%e5%ae%9a%e4%b9%89%e8%80%85%e4%b8%8e%e8%b0%83%e7%94%a8%e8%80%85.html" rel="bookmark" class="crp_title">pl/sql的定义者与调用者</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/11/plsql-%e5%b8%b8%e7%94%a8%e8%af%ad%e6%b3%95.html" rel="bookmark" class="crp_title">pl/sql 常用语法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/08/ora-01031-insufficient-privileges.html" rel="bookmark" class="crp_title">ORA-01031: insufficient privileges</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2023/10/ora-600-12807-recovery.html" rel="bookmark" class="crp_title">ORA-600 12807（CON$.CON#达到最大值） 处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/07/ora-04091.html" rel="bookmark" class="crp_title">触发器引起ORA-04091</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/9i%e4%b8%ad%e6%b8%85%e9%99%a4%e7%89%b9%e5%ae%9a%e8%a1%a8%e7%9b%b8%e5%85%b3%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92.html" rel="bookmark" class="crp_title">9I中清除特定表相关执行计划</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/%e9%80%9a%e8%bf%87%e4%bf%ae%e6%94%b9col-col%e6%94%b9%e5%8f%98%e5%88%97%e5%b1%95%e7%a4%ba%e9%a1%ba%e5%ba%8f.html" rel="bookmark" class="crp_title">通过修改col$.col#改变列展示顺序</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2012/06/%e5%ae%9e%e7%8e%b0trigger%e9%9b%86%e4%b8%ad%e8%ae%b0%e5%bd%95%e6%89%80%e6%9c%89%e5%ba%93ddl%e6%93%8d%e4%bd%9c.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ORACLE 十进制与二进制互转函数</title>
		<link>https://www.xifenfei.com/2012/04/oracle-%e5%8d%81%e8%bf%9b%e5%88%b6%e4%b8%8e%e4%ba%8c%e8%bf%9b%e5%88%b6%e4%ba%92%e8%bd%ac%e5%87%bd%e6%95%b0.html</link>
		<comments>https://www.xifenfei.com/2012/04/oracle-%e5%8d%81%e8%bf%9b%e5%88%b6%e4%b8%8e%e4%ba%8c%e8%bf%9b%e5%88%b6%e4%ba%92%e8%bd%ac%e5%87%bd%e6%95%b0.html#comments</comments>
		<pubDate>Thu, 12 Apr 2012 08:16:13 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=2897</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2012/04/oracle-%e5%8d%81%e8%bf%9b%e5%88%b6%e4%b8%8e%e4%ba%8c%e8%bf%9b%e5%88%b6%e4%ba%92%e8%bd%ac%e5%87%bd%e6%95%b0.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2012/04/oracle-%e5%8d%81%e8%bf%9b%e5%88%b6%e4%b8%8e%e4%ba%8c%e8%bf%9b%e5%88%b6%e4%ba%92%e8%bd%ac%e5%87%bd%e6%95%b0.html" target="_blank">ORACLE 十进制与二进制互转函数</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p>十进制转换二进制</p>
<pre class="brush: sql; title: ; notranslate">
CREATE OR REPLACE FUNCTION NUMBER_TO_BIT(V_NUM NUMBER) 
RETURN VARCHAR IS V_RTN VARCHAR(8);--注意返回列长度
  V_N1  NUMBER;
  V_N2  NUMBER;
BEGIN
V_N1 := V_NUM;
    LOOP
      V_N2  := MOD(V_N1, 2);
      V_N1  := ABS(TRUNC(V_N1 / 2));
      V_RTN := TO_CHAR(V_N2) || V_RTN;
      EXIT WHEN V_N1 = 0;
    END LOOP;
--返回二进制长度
 SELECT lpad(V_RTN,8,0) 
    INTO   V_RTN
    FROM dual;
return V_RTN;
end;

SQL&gt; select NUMBER_TO_BIT(208) from dual;

NUMBER_TO_BIT(208)
-----------------------------
11010000
</pre>
<p>二进制转换十进制</p>
<pre class="brush: sql; title: ; notranslate">
CREATE OR REPLACE FUNCTION BIT_TO_NUMBER(P_BIN IN VARCHAR2) RETURN NUMBER AS
  V_SQL    VARCHAR2(30000) := 'SELECT BIN_TO_NUM(';
  V_RETURN NUMBER;
BEGIN
  IF LENGTH(P_BIN) &gt;= 256 THEN
    RAISE_APPLICATION_ERROR(-20001, 'INPUT BIN TOO LONG!');
  END IF;
  IF LTRIM(P_BIN, '01') IS NOT NULL THEN
    RAISE_APPLICATION_ERROR(-20002, 'INPUT STR IS NOT VALID BIN VALUE!');
  END IF;
  FOR I IN 1 .. LENGTH(P_BIN) LOOP
    V_SQL := V_SQL || SUBSTR(P_BIN, I, 1) || ',';
  END LOOP;
  V_SQL := RTRIM(V_SQL, ',') || ') FROM DUAL';
  EXECUTE IMMEDIATE V_SQL
    INTO V_RETURN;
  RETURN V_RETURN;
END;

SQL&gt; SELECT BIT_TO_NUMBER('11010000') FROM DUAL;

BIT_TO_NUMBER('11010000')
-------------------------
                      208
</pre>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/05/sql_id%e5%92%8chash-value%e7%9a%84%e9%83%a8%e5%88%86%e8%bd%ac%e6%8d%a2.html" rel="bookmark" class="crp_title">sql_id和hash value的部分转换</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/12/%e8%a7%a6%e5%8f%91%e5%99%a8%e5%ae%9e%e7%8e%b0%e6%8c%87%e5%ae%9a%e7%94%a8%e6%88%b7%e7%99%bb%e5%bd%95oracle.html" rel="bookmark" class="crp_title">触发器实现指定用户登录oracle</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/11/plsql-%e5%b8%b8%e7%94%a8%e8%af%ad%e6%b3%95.html" rel="bookmark" class="crp_title">pl/sql 常用语法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/06/long%e6%9f%a5%e8%af%a2%e7%bb%93%e6%9e%9c%e8%bd%ac%e6%8d%a2%e4%b8%bavarchar2%e7%b1%bb%e5%9e%8b.html" rel="bookmark" class="crp_title">long查询结果转换为varchar2类型</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/06/oracle%e5%88%86%e5%89%b2%e5%87%bd%e6%95%b0.html" rel="bookmark" class="crp_title">oracle分割函数</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/%e4%bf%ae%e6%94%b9clob%e5%ad%97%e6%ae%b5%e5%b9%b6%e6%8f%92%e5%85%a5%e6%96%b0%e8%a1%a8.html" rel="bookmark" class="crp_title">修改clob字段并插入新表</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/02/table%e5%87%bd%e6%95%b0%e7%94%a8%e6%b3%95.html" rel="bookmark" class="crp_title">table()函数用法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/08/%e7%b2%be%e5%bd%a9sql%e8%af%ad%e5%8f%a5.html" rel="bookmark" class="crp_title">精彩SQL语句</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/05/%e5%9c%a8sql%e8%af%ad%e5%8f%a5%e4%b8%ad%e9%80%9a%e8%bf%87with-%e5%ae%9a%e4%b9%89plsql-%e5%87%bd%e6%95%b0.html" rel="bookmark" class="crp_title">ORACLE 12C SQL语句中通过with 定义PL/SQL 函数</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2015/01/%e9%80%9a%e8%bf%87dbms_crypto%e5%8c%85%e5%af%b9%e8%a1%a8%e6%95%8f%e6%84%9f%e5%ad%97%e6%ae%b5%e8%bf%9b%e8%a1%8c%e5%8a%a0%e5%af%86.html" rel="bookmark" class="crp_title">通过DBMS_CRYPTO包对表敏感字段进行加密</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/%e6%b8%85%e7%90%86%e8%a1%a8%e9%83%a8%e5%88%86%e6%95%b0%e6%8d%ae%e6%96%b9%e6%b3%95.html" rel="bookmark" class="crp_title">清理表部分数据方法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/05/%e6%89%b9%e9%87%8fkill-session%e5%ae%9e%e7%8e%b0%e8%84%9a%e6%9c%ac.html" rel="bookmark" class="crp_title">批量kill session实现脚本</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2012/04/oracle-%e5%8d%81%e8%bf%9b%e5%88%b6%e4%b8%8e%e4%ba%8c%e8%bf%9b%e5%88%b6%e4%ba%92%e8%bd%ac%e5%87%bd%e6%95%b0.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>lob类型数据转换为系统文件</title>
		<link>https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html</link>
		<comments>https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html#comments</comments>
		<pubDate>Tue, 20 Mar 2012 16:01:12 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=2724</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html" target="_blank">lob类型数据转换为系统文件</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p><strong>1.插入一条blob数据</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create directory ULTLOBDIR as '/home/oracle';

Directory created.

SQL&gt; create table blobtest(col1 BLOB);

Table created.

SQL&gt; declare
a_blob BLOB;
  2    3  bfile_name BFILE := BFILENAME('ULTLOBDIR','tt.txt.bak');
  4  begin
  5  insert into blobtest values (empty_blob())
  6  returning col1 into a_blob;
  7  dbms_lob.fileopen(bfile_name);
  8  dbms_lob.loadfromfile(a_blob, bfile_name, dbms_lob.getlength(bfile_name));
  9  dbms_lob.fileclose(bfile_name);
 10  commit;
 11  end;
 12  /

PL/SQL procedure successfully completed.

SQL&gt; select dbms_lob.getlength(col1) from blobtest;

DBMS_LOB.GETLENGTH(COL1)
------------------------
                    4829

SQL&gt; !pwd
/home/oracle

SQL&gt; !ls -l tt.txt.bak
-rw-r--r-- 1 oracle oinstall 4829 03-19 17:26 tt.txt.bak
</pre>
<p><strong>2.创建存储过程</strong></p>
<pre class="brush: sql; title: ; notranslate">
CREATE OR REPLACE PROCEDURE RETRIEVE_LOB_TO_FILE(TEMP_BLOB IN BLOB,
                                                 FILE_PATH IN VARCHAR2,
                                                 FILE_NAME IN VARCHAR2) IS
  DATA_BUFFER   RAW(32767);
  POSITION      INTEGER := 1;
  FILEHANDLE    UTL_FILE.FILE_TYPE;
  ERROR_NUMBER  NUMBER;
  ERROR_MESSAGE VARCHAR2(100);
  BLOB_LENGTH   INTEGER;
  CHUNK_SIZE    BINARY_INTEGER := 32767;
BEGIN
  BLOB_LENGTH := DBMS_LOB.GETLENGTH(TEMP_BLOB);
  FILEHANDLE  := UTL_FILE.FOPEN(FILE_PATH, FILE_NAME, 'wb', 1024);
  WHILE POSITION &lt; BLOB_LENGTH LOOP
    DBMS_LOB.READ(TEMP_BLOB, CHUNK_SIZE, POSITION, DATA_BUFFER);
    UTL_FILE.PUT_RAW(FILEHANDLE, DATA_BUFFER);
    POSITION    := POSITION + CHUNK_SIZE;
    DATA_BUFFER := NULL;
  END LOOP;
  UTL_FILE.FCLOSE(FILEHANDLE);
EXCEPTION
  WHEN OTHERS THEN
    BEGIN
      ERROR_NUMBER  := SQLCODE;
      ERROR_MESSAGE := SUBSTR(SQLERRM, 1, 100);
      DBMS_OUTPUT.PUT_LINE('Error #: ' || ERROR_NUMBER);
      DBMS_OUTPUT.PUT_LINE('Error Message: ' || ERROR_MESSAGE);
      UTL_FILE.FCLOSE_ALL;
    END;
END;
/
</pre>
<p><strong>3.测试读取blob到系统</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; declare 
  2  tmp_blob blob default empty_blob(); 
  3  begin 
  4  dbms_lob.createtemporary(tmp_blob, true); 
  5  select col1 into tmp_blob from blobtest; 
  6  retrieve_lob_to_file (tmp_blob, 'ULTLOBDIR','xifenfei.txt'); 
  7  end;
  8  /

PL/SQL procedure successfully completed.

SQL&gt; !pwd
/home/oracle

SQL&gt; !ls -l xifenfei.txt
-rw-r--r-- 1 oracle oinstall 4829 03-20 23:44 xifenfei.txt
</pre>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/02/%e5%9c%a8sqlplus%e4%b8%ad%e6%93%8d%e4%bd%9cblob%e5%92%8cclob.html" rel="bookmark" class="crp_title">在sqlplus中操作blob和clob</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/07/dul-10-export_modetrue%e5%8a%9f%e8%83%bd%e5%a2%9e%e5%bc%ba.html" rel="bookmark" class="crp_title">dul 10 export_mode=true功能增强</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/%e4%bf%ae%e6%94%b9clob%e5%ad%97%e6%ae%b5%e5%b9%b6%e6%8f%92%e5%85%a5%e6%96%b0%e8%a1%a8.html" rel="bookmark" class="crp_title">修改clob字段并插入新表</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2022/05/plsql-insert-blob.html" rel="bookmark" class="crp_title">plsql 插入blob</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/07/%e4%bd%bf%e7%94%a8flashback-query%e6%81%a2%e5%a4%8d%e8%a2%ab%e5%88%a0%e9%99%a4plsql.html" rel="bookmark" class="crp_title">使用flashback query恢复被删除plsql</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2019/04/sql-plan-baseline.html" rel="bookmark" class="crp_title">sql plan baseline简单介绍</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2026/02/expdp-xml-ora-22924.html" rel="bookmark" class="crp_title">expdp导出xml列报ORA-22924故障处理</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/11/plsql-%e5%b8%b8%e7%94%a8%e8%af%ad%e6%b3%95.html" rel="bookmark" class="crp_title">pl/sql 常用语法</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/%e4%bd%bf%e7%94%a8wrap%e5%8a%a0%e5%af%86plsql%e4%bb%a3%e7%a0%81.html" rel="bookmark" class="crp_title">使用wrap加密pl/sql代码</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2019/03/scn-compatibility.html" rel="bookmark" class="crp_title">SCN Compatibility问题汇总-2019年6月23日</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/08/ora-01031-insufficient-privileges.html" rel="bookmark" class="crp_title">ORA-01031: insufficient privileges</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/10/sqlplus-%e4%bd%bf%e7%94%a8%e5%b0%8f%e6%8a%80%e5%b7%a7.html" rel="bookmark" class="crp_title">sqlplus 使用小技巧</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2012/03/lob%e7%b1%bb%e5%9e%8b%e6%95%b0%e6%8d%ae%e8%bd%ac%e6%8d%a2%e4%b8%ba%e7%b3%bb%e7%bb%9f%e6%96%87%e4%bb%b6.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LNNVL函数使用</title>
		<link>https://www.xifenfei.com/2012/03/lnnvl%e5%87%bd%e6%95%b0%e4%bd%bf%e7%94%a8.html</link>
		<comments>https://www.xifenfei.com/2012/03/lnnvl%e5%87%bd%e6%95%b0%e4%bd%bf%e7%94%a8.html#comments</comments>
		<pubDate>Tue, 06 Mar 2012 11:06:37 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=2610</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2012/03/lnnvl%e5%87%bd%e6%95%b0%e4%bd%bf%e7%94%a8.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2012/03/lnnvl%e5%87%bd%e6%95%b0%e4%bd%bf%e7%94%a8.html" target="_blank">LNNVL函数使用</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p><strong>LNNVL官方解释</strong><br />
LNNVL provides a concise way to evaluate a condition when one or both operands of the condition may be null. The function can be used only in the WHERE clause of a query. It takes as an argument a condition and returns TRUE if the condition is FALSE or UNKNOWN and FALSE if the condition is TRUE. LNNVL can be used anywhere a scalar expression can appear, even in contexts where the IS [NOT] NULL, AND, or OR conditions are not valid but would otherwise be required to account for potential nulls. Oracle Database sometimes uses the LNNVL function internally in this way to rewrite NOT IN conditions as NOT EXISTS conditions. In such cases, output from EXPLAIN PLAN shows this operation in the plan table output. The condition can evaluate any scalar values but cannot be a compound condition containing AND, OR, or BETWEEN.<br />
<a href="//www.xifenfei.com/wp-content/uploads/2012/03/lnnvl.jpg"><img src="//www.xifenfei.com/wp-content/uploads/2012/03/lnnvl.jpg" alt="" title="lnnvl" width="953" height="187" class="aligncenter size-full wp-image-2611" /></a><br />
<strong>LNNVL官方解释翻译</strong><br />
lnnvl用于某个语句的where子句中的条件，如果条件为true就返回false；如果条件为UNKNOWN或者false就返回true。该函数不能用于复合条件如AND, OR, or BETWEEN中。<br />
<br />
<strong>模拟测试环境</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; create table xifenfei(name varchar2(20),year number);

Table created.

SQL&gt; insert into xifenfei values('xifenfei2001',2001);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2002',2002);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2003',2003);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2004',2004);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2005',2005);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2006',2006);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2007',2007);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2008',null);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2009',2009);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2010',2010);

1 row created.

SQL&gt; insert into xifenfei values('xifenfei2011',2011);

1 row created.

SQL&gt; commit;

Commit complete.

SQL&gt; select * from xifenfei;

NAME                       YEAR
-------------------- ----------
xifenfei2001               2001
xifenfei2002               2002
xifenfei2003               2003
xifenfei2004               2004
xifenfei2005               2005
xifenfei2006               2006
xifenfei2007               2007
xifenfei2008
xifenfei2009               2009
xifenfei2010               2010
xifenfei2011               2011

11 rows selected.
</pre>
<p><strong>几种情况测试说明</strong></p>
<pre class="brush: sql; title: ; notranslate">
--年份小于2009(lnnvl表示年份大于或者2009包含null)
SQL&gt; select * from xifenfei where lnnvl(year&lt;2009);

NAME                       YEAR
-------------------- ----------
xifenfei2008
xifenfei2009               2009
xifenfei2010               2010
xifenfei2011               2011

--year不为null(lnnvl表示年份为null)
SQL&gt; select * from xifenfei where lnnvl(year is not null);

NAME                       YEAR
-------------------- ----------
xifenfei2008

--年份为null(lnnvl表示年份不为null)
SQL&gt; select * from xifenfei where lnnvl(year is  null);

NAME                       YEAR
-------------------- ----------
xifenfei2001               2001
xifenfei2002               2002
xifenfei2003               2003
xifenfei2004               2004
xifenfei2005               2005
xifenfei2006               2006
xifenfei2007               2007
xifenfei2009               2009
xifenfei2010               2010
xifenfei2011               2011

10 rows selected.

--年份为12345(lnnvl表示年份不为12345)
SQL&gt; select * from xifenfei where lnnvl(year =12345);

NAME                       YEAR
-------------------- ----------
xifenfei2001               2001
xifenfei2002               2002
xifenfei2003               2003
xifenfei2004               2004
xifenfei2005               2005
xifenfei2006               2006
xifenfei2007               2007
xifenfei2008
xifenfei2009               2009
xifenfei2010               2010
xifenfei2011               2011

11 rows selected.

--年份不为12345(lnnvl表示年份为12345或者null)
SQL&gt; select * from xifenfei where lnnvl(year !=12345);

NAME                       YEAR
-------------------- ----------
xifenfei2008
</pre>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/12/oracle-12c-%e6%94%af%e6%8c%81multiple-partitions%e5%90%8c%e6%97%b6%e6%93%8d%e4%bd%9c.html" rel="bookmark" class="crp_title">ORACLE 12C 支持multiple partitions同时操作</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/04/12c-%e4%bd%bf%e7%94%a8sequence%e4%bd%9c%e4%b8%ba%e5%88%97%e9%bb%98%e8%ae%a4%e5%80%bc.html" rel="bookmark" class="crp_title">12c 使用sequence作为列默认值</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/inexists%e5%92%8cnot-innot-exists%e8%af%ad%e6%84%8f%e6%8e%a2%e8%ae%a8.html" rel="bookmark" class="crp_title">in/exists和not in/not exists语意探讨</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/multiple-table-cache-group%e9%85%8d%e7%bd%ae.html" rel="bookmark" class="crp_title">Multiple-table cache group配置</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2017/11/move-lob-index-unusable.html" rel="bookmark" class="crp_title">move lob导致index失效</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/08/oracle-%e6%8f%92%e5%85%a5%e5%90%ab%e5%ad%97%e7%ac%a6%e4%b8%b2.html" rel="bookmark" class="crp_title">oracle 插入含&#038;字符串</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/12/orcle-12c-%e5%a2%9e%e5%8a%a0%e5%88%97%e6%97%a0%e9%bb%98%e8%ae%a4%e5%80%bc.html" rel="bookmark" class="crp_title">ORCLE 12C 增加列,无默认值</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/03/%e9%80%9a%e8%bf%87%e4%bf%ae%e6%94%b9col-col%e6%94%b9%e5%8f%98%e5%88%97%e5%b1%95%e7%a4%ba%e9%a1%ba%e5%ba%8f.html" rel="bookmark" class="crp_title">通过修改col$.col#改变列展示顺序</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/12/instead-of%e8%a7%a6%e5%8f%91%e5%99%a8%e5%ae%9e%e7%8e%b0%e8%a7%86%e5%9b%bedml%e6%93%8d%e4%bd%9c.html" rel="bookmark" class="crp_title">INSTEAD OF触发器实现视图DML操作</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2010/08/mysql-%e4%bd%bf%e7%94%a8%e4%ba%8c%e8%bf%9b%e5%88%b6%e6%97%a5%e5%bf%97%e6%96%87%e4%bb%b6%e6%81%a2%e5%a4%8d%e6%95%b0%e6%8d%ae%e5%ba%93.html" rel="bookmark" class="crp_title">mysql 使用二进制日志文件恢复数据库</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/08/%e5%88%86%e5%8c%ba%e9%bb%98%e8%ae%a4segment%e5%a4%a7%e5%b0%8f%e5%8f%98%e5%8c%9664k-8m.html" rel="bookmark" class="crp_title">分区默认segment大小变化(64k&#8212;>8M)</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/09/%e5%9c%a8win%e4%b8%ad%e8%bf%90%e8%a1%8cbbed%e7%a8%8b%e5%ba%8f.html" rel="bookmark" class="crp_title">在win中运行bbed程序</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2012/03/lnnvl%e5%87%bd%e6%95%b0%e4%bd%bf%e7%94%a8.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>创建含sysdate的函数index</title>
		<link>https://www.xifenfei.com/2012/01/%e5%88%9b%e5%bb%ba%e5%90%absysdate%e7%9a%84%e5%87%bd%e6%95%b0index.html</link>
		<comments>https://www.xifenfei.com/2012/01/%e5%88%9b%e5%bb%ba%e5%90%absysdate%e7%9a%84%e5%87%bd%e6%95%b0index.html#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:07:14 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>
		<category><![CDATA[ORA-01743]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=2334</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2012/01/%e5%88%9b%e5%bb%ba%e5%90%absysdate%e7%9a%84%e5%87%bd%e6%95%b0index.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2012/01/%e5%88%9b%e5%bb%ba%e5%90%absysdate%e7%9a%84%e5%87%bd%e6%95%b0index.html" target="_blank">创建含sysdate的函数index</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p><strong>1.模拟环境</strong><br />
创建表插入数据库</p>
<pre class="brush: sql; title: ; notranslate">[oracle@node1 ~]$ sqlplus chf/xifenfei

SQL*Plus: Release 11.2.0.3.0 Production on Mon Jan 9 16:27:19 2012

Copyright (c) 1982, 2011, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Data Mining,
Oracle Database Vault and Real Application Testing options

SQL&gt; create table t_xifenfei(id number,intime date);

Table created.

SQL&gt; DECLARE
  2  i NUMBER;
  3  BEGIN
  4    FOR i IN 1..1000 LOOP
  5      INSERT INTO t_xifenfei VALUES(i,SYSDATE-i);
  6      END LOOP;
  7      COMMIT;
  8  END;
  9  /

PL/SQL procedure successfully completed.

SQL&gt; select count(*) from t_xifenfei;

  COUNT(*)
----------
      1000


SQL&gt; exec dbms_stats.gather_table_stats(USER,'T_XIFENFEI',cascade =&gt; TRUE);

PL/SQL procedure successfully completed.
</pre>
<p><strong>2.无index查询</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; set autot trace exp stat
Execution Plan
----------------------------------------------------------
Plan hash value: 548923532

--------------------------------------------------------------------------------
| Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |            |    10 |   120 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| T_XIFENFEI |    10 |   120 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(NVL(&quot;INTIME&quot;,SYSDATE@!)&gt;=TO_DATE(' 2011-12-31 00:00:00',
              'syyyy-mm-dd hh24:mi:ss'))


Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          7  consistent gets
          0  physical reads
          0  redo size
        770  bytes sent via SQL*Net to client
        519  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          9  rows processed

SQL&gt; set autot off
</pre>
<p>这里只是做了一个简单的查询，因为这个nvl(intime,sysdate)的条件，无法使用正常的index，所以没有建立intime索引的测试。<br />
<br />
<strong>3.尝试创建index</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt;  create index in_t_xifenfei on t_xifenfei (nvl(intime,sysdate)) online nologging;
 create index in_t_xifenfei on t_xifenfei (nvl(intime,sysdate)) online nologging
                                                      *
ERROR at line 1:
ORA-01743: only pure functions can be indexed


SQL&gt; !oerr ora 1743
01743, 00000, &quot;only pure functions can be indexed&quot;
// *Cause: The indexed function uses SYSDATE or the user environment.
// *Action: PL/SQL functions must be pure (RNDS, RNPS, WNDS, WNPS).  SQL
//          expressions must not use SYSDATE, USER, USERENV(), or anything
//          else dependent on the session state.  NLS-dependent functions
//          are OK.
--因为含有sysdate创建函数index失败


SQL&gt; CREATE OR REPLACE FUNCTION f_xifenfei (itime DATE)
  2  RETURN DATE
  3  IS
  4  otime DATE;
  5  BEGIN 
  6    otime:=NVL(itime,SYSDATE);
  7    RETURN otime;
  8  END;
  9  /

Function created.
--想采用自定义函数屏蔽掉sysdate在创建index时候的影响

SQL&gt;  create index in_t_xifenfei on t_xifenfei (f_xifenfei(intime)) online nologging;
 create index in_t_xifenfei on t_xifenfei (f_xifenfei(intime)) online nologging
                                           *
ERROR at line 1:
ORA-30553: The function is not deterministic


SQL&gt; !oerr ora 30553
30553, 00000, &quot;The function is not deterministic&quot; 
// *Cause:  The function on which the index is defined is not deterministic 
// *Action: If the function is deterministic, mark it DETERMINISTIC.  If it
//          is not deterministic (it depends on package state, database state,
//          current time, or anything other than the function inputs) then
//          do not create the index.  The values returned by a deterministic
//          function should not change even when the function is rewritten or
//          recompiled.
--因为函数缺少deterministic不能使用于index上

SQL&gt; CREATE OR REPLACE FUNCTION f_xifenfei (itime DATE)
  2  RETURN DATE deterministic
  3  IS
  4  otime DATE;
  5  BEGIN 
  6    otime:=NVL(itime,SYSDATE);
  7    RETURN otime;
  8  END;
  9  /

Function created.

SQL&gt; create index in_t_xifenfei on t_xifenfei (f_xifenfei(intime)) online nologging;

Index created.
--创建函数index成功

SQL&gt; exec dbms_stats.gather_table_stats(USER,'T_XIFENFEI',cascade =&gt; TRUE);

PL/SQL procedure successfully completed.
</pre>
<p><strong>4.再次查询</strong><br />
确定已经使用函数index，达到在index中使用sysdate函数index的目的。</p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; set autot on  exp stat
SQL&gt; select * from t_xifenfei where f_xifenfei(intime)&gt;=to_date('2011-12-31','yyyy-mm-dd');

Execution Plan
----------------------------------------------------------
Plan hash value: 2005404611

---------------------------------------------------------------------------------------------
| Id  | Operation                   | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------

|   0 | SELECT STATEMENT            |               |    10 |   200 |     3   (0)| 00:00:01 |

|   1 |  TABLE ACCESS BY INDEX ROWID| T_XIFENFEI    |    10 |   200 |     3   (0)| 00:00:01 |

|*  2 |   INDEX RANGE SCAN          | IN_T_XIFENFEI |    10 |       |     2   (0)| 00:00:01 |

---------------------------------------------------------------------------------------------


Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access(&quot;CHF&quot;.&quot;F_XIFENFEI&quot;(&quot;INTIME&quot;)&gt;=TO_DATE(' 2011-12-31 00:00:00',
              'syyyy-mm-dd hh24:mi:ss'))


Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          5  consistent gets
          0  physical reads
          0  redo size
        770  bytes sent via SQL*Net to client
        519  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          9  rows processed
</pre>
<p><strong>5.总结说明</strong><br />
5.1)通过函数屏蔽函数index的时候，不能使用sysdate<br />
5.2)在创建函数时，需要指定deterministic关键字</p>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/12/%e5%88%9b%e5%bb%ba%e6%94%af%e6%8c%81null-index.html" rel="bookmark" class="crp_title">创建包含null值index</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e4%b8%ad%e5%b8%b8%e8%a7%81index%e8%ae%bf%e9%97%ae%e6%96%b9%e5%bc%8f.html" rel="bookmark" class="crp_title">执行计划中常见index访问方式</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/hint%e6%8c%87%e5%ae%9aindex%e7%9a%84%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3.html" rel="bookmark" class="crp_title">hint指定index的深入理解</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/05/bind-variable-peeking-%e6%b5%8b%e8%af%95.html" rel="bookmark" class="crp_title">Bind Variable Peeking 测试</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/04/12c-top-n-sql%e5%ae%9e%e7%8e%b0%e5%88%86%e9%a1%b5%e5%8a%9f%e8%83%bd.html" rel="bookmark" class="crp_title">ORACLE 12C TOP N SQL实现分页功能</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2017/06/_optimizer_null_aware_antijoin-not-in.html" rel="bookmark" class="crp_title">_optimizer_null_aware_antijoin和not in效率</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/05/sql-profile-%e4%bd%bf%e7%94%a8.html" rel="bookmark" class="crp_title">sql profile 使用</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/09/oracle%e7%9b%b4%e6%96%b9%e5%9b%be%e7%90%86%e8%a7%a3%e4%b8%8e%e5%ae%9e%e9%aa%8c.html" rel="bookmark" class="crp_title">Oracle直方图理解与实验</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2014/03/%e5%90%abis-null-sql%e8%af%ad%e5%8f%a5%e4%bc%98%e5%8c%96.html" rel="bookmark" class="crp_title">含is null sql语句优化</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2014/10/11g%e4%b8%ad-connect-by-%e8%af%ad%e5%8f%a5%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e6%94%b9%e5%8f%98.html" rel="bookmark" class="crp_title">11g中 connect by 语句执行计划改变</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/09/10g%e6%96%b0%e5%a2%9e%e5%88%97%e6%96%b9%e5%bc%8f%e6%8c%87%e5%ae%9ahint.html" rel="bookmark" class="crp_title">10g新增列方式指定HINT</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/07/select-maxamina-from-table%e4%bc%98%e5%8c%96.html" rel="bookmark" class="crp_title">select max(id),min(id) from table优化</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2012/01/%e5%88%9b%e5%bb%ba%e5%90%absysdate%e7%9a%84%e5%87%bd%e6%95%b0index.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>记一次含AND-EQUAL执行计划调优</title>
		<link>https://www.xifenfei.com/2011/12/%e8%ae%b0%e4%b8%80%e6%ac%a1%e5%90%aband-equal%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e8%b0%83%e4%bc%98.html</link>
		<comments>https://www.xifenfei.com/2011/12/%e8%ae%b0%e4%b8%80%e6%ac%a1%e5%90%aband-equal%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e8%b0%83%e4%bc%98.html#comments</comments>
		<pubDate>Thu, 29 Dec 2011 01:58:03 +0000</pubDate>
		<dc:creator><![CDATA[惜分飞]]></dc:creator>
				<category><![CDATA[Oracle 开发]]></category>

		<guid isPermaLink="false">https://www.xifenfei.com/?p=2280</guid>
		<description><![CDATA[联系：手机/微信(+86 17813235971) QQ(107644445)  &#8230; <a href="https://www.xifenfei.com/2011/12/%e8%ae%b0%e4%b8%80%e6%ac%a1%e5%90%aband-equal%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e8%b0%83%e4%bc%98.html">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="xifenfeicopyright">
<p>联系：<a href="https://www.xifenfei.com/about_xifenfei" target="_blank">手机/微信(+86 17813235971)   QQ(107644445)</a><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&#038;uin=107644445&#038;site=qq&#038;menu=yes"><img src="https://www.xifenfei.com/wp-content/themes/img/site_qq.jpg" alt="QQ咨询惜分飞" title="QQ咨询惜分飞"/></a></p>
<p>标题：<a href="https://www.xifenfei.com/2011/12/%e8%ae%b0%e4%b8%80%e6%ac%a1%e5%90%aband-equal%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e8%b0%83%e4%bc%98.html" target="_blank">记一次含AND-EQUAL执行计划调优</a></p>
<p>作者：<a href="https://www.xifenfei.com" target="_blank">惜分飞</a>©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]</p>
</div>
<p><strong>1.数据库版本</strong></p>
<pre class="brush: sql; title: ; notranslate">SQL&gt; select * from v$version;

BANNER
----------------------------------------------------------------
Oracle9i Enterprise Edition Release 9.2.0.4.0 - Production
PL/SQL Release 9.2.0.4.0 - Production
CORE    9.2.0.3.0       Production
TNS for Linux: Version 9.2.0.4.0 - Production
NLSRTL Version 9.2.0.4.0 - Production
</pre>
<p><strong>2.发现含有AND-EQUAL执行计划</strong></p>
<pre class="brush: sql; title: ; notranslate">
SQL&gt; SELECT 
  2  COUNT(TABXNPRESM1_.DETAIL_ID) AS X0_0_
  3    FROM QXTDEV1.TAB_XN_PRESMS TABXNPRESM0_, QXTDEV1.TAB_XN_PRESMS_DETAIL TABXNPRESM1_
  4  WHERE  (TABXNPRESM0_.COMPANY_ID = 346240)
  5     AND (TABXNPRESM0_.EMPLOYEE_ID = 0)
  6     AND (TABXNPRESM0_.PRE_TIME &gt;= TO_DATE('2011/12/25', 'yyyy/mm/dd'))
  7     AND (TABXNPRESM0_.PRE_TIME &lt; TO_DATE('2011/12/26', 'yyyy/mm/dd') + 1)
  8     AND ((TABXNPRESM0_.SEND_TYPE = 1) OR (TABXNPRESM0_.SEND_TYPE = 0))
  9     AND ((TABXNPRESM1_.RESULT = -1) OR (TABXNPRESM1_.RESULT = 0))
 10     AND (TABXNPRESM0_.PRE_ID = TABXNPRESM1_.PRE_ID);

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=11 Card=1 Bytes=40)
   1    0   SORT (AGGREGATE)
   2    1     TABLE ACCESS (BY INDEX ROWID) OF 'TAB_XN_PRESMS_DETAIL'(Cost=3 Card=2 Bytes=30)
   3    2       NESTED LOOPS (Cost=11 Card=1 Bytes=40)
   4    3         TABLE ACCESS (BY INDEX ROWID) OF 'TAB_XN_PRESMS' (Cost=8 Card=1 Bytes=25)
   5    4           AND-EQUAL
   6    5             INDEX (RANGE SCAN) OF 'IDX_XN_PRESMS_2' (NON-UNIQUE)
   7    5             INDEX (RANGE SCAN) OF 'IDX_XN_PRESMS_1' (NON-UNIQUE) (Cost=4 Card=638)
   8    3         INDEX (RANGE SCAN) OF 'IDX_XN_PRESMS_DETAIL' (NON-UNIQUE) (Cost=2 Card=2)



Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
     272188  consistent gets
          0  physical reads
          0  redo size
        375  bytes sent via SQL*Net to client
        503  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed
</pre>
<p><strong>3.关于AND-EQUAL解释</strong><br />
If the WHERE clauses uses columns of many single-column indexes, then Oracle executes the statement by performing a range scan on each index to retrieve the rowids of the rows that satisfy each condition. Oracle then merges the sets of rowids to obtain a set of rowids of rows that satisfy all conditions. Oracle then accesses the table using these rowids.<br />
Oracle can merge up to five indexes. If the WHERE clause uses columns of more than five single-column indexes, then Oracle merges five of them, accesses the table by rowid, and then tests the resulting rows to determine whether they satisfy the remaining conditions before returning them.<br />
大概的意思是当where条件后面含有多个列的单列索引时(不超过5个)，会先得到每个条件的rowid，然后这些rowid进行merges，得到一个rowid的结果集，最后根据这些rowid取表中记录。<br />
<br />
<strong>4.表/列/索引相关信息</strong></p>
<pre class="brush: sql; title: ; notranslate">
--index和列信息
SQL&gt; SELECT INDEX_NAME, TABLE_NAME, COLUMN_NAME
  2    FROM USER_IND_COLUMNS
  3   WHERE TABLE_NAME IN ('TAB_XN_PRESMS', 'TAB_XN_PRESMS_DETAIL');
 
INDEX_NAME                     TABLE_NAME                     COLUMN_NAME
------------------------------ ------------------------------ --------------------
IDX_XN_PRESMS_1                TAB_XN_PRESMS                  COMPANY_ID
IDX_XN_PRESMS_2                TAB_XN_PRESMS                  EMPLOYEE_ID
IDX_XN_PRESMS_3                TAB_XN_PRESMS                  PRE_TIME
PK_TAB_XN_PRESMS               TAB_XN_PRESMS                  PRE_ID
IDX_XN_PRESMS_4                TAB_XN_PRESMS                  SEND_TYPE
IDX_XN_PRESMS_DETAIL           TAB_XN_PRESMS_DETAIL           PRE_ID
IDX_XN_PRESMS_DETAIL_2         TAB_XN_PRESMS_DETAIL           SEND_TIME
PK_TAB_XN_PRESMS_DETAIL        TAB_XN_PRESMS_DETAIL           DETAIL_ID
 
8 rows selected

--index的统计信息
SQL&gt; SELECT TABLE_NAME,
  2         INDEX_NAME,
  3         TO_CHAR(LAST_ANALYZED, 'yyyy-mm-dd hh24:mi:ss')
  4    FROM USER_INDEXES
  5   WHERE TABLE_NAME IN ('TAB_XN_PRESMS', 'TAB_XN_PRESMS_DETAIL');
 
TABLE_NAME                     INDEX_NAME                     TO_CHAR(LAST_ANALYZED,'YYYY-MM
------------------------------ ------------------------------ ------------------------------
TAB_XN_PRESMS                  IDX_XN_PRESMS_1                2011-12-29 09:25:32
TAB_XN_PRESMS                  IDX_XN_PRESMS_2                2011-12-29 09:25:35
TAB_XN_PRESMS                  IDX_XN_PRESMS_3                2011-12-29 09:25:39
TAB_XN_PRESMS                  IDX_XN_PRESMS_4                2011-12-29 09:25:21
TAB_XN_PRESMS_DETAIL           IDX_XN_PRESMS_DETAIL           2011-12-29 09:20:03
TAB_XN_PRESMS_DETAIL           IDX_XN_PRESMS_DETAIL_2         2011-12-29 09:20:01
TAB_XN_PRESMS                  PK_TAB_XN_PRESMS               2011-12-29 09:25:46
TAB_XN_PRESMS_DETAIL           PK_TAB_XN_PRESMS_DETAIL        2011-12-29 09:20:02
 
8 rows selected

--列的唯一度情况
SQL&gt;  SELECT TABLE_NAME, COLUMN_NAME, NUM_DISTINCT
  2     FROM USER_TAB_COLS
  3    WHERE (TABLE_NAME, COLUMN_NAME) IN
  4          (SELECT TABLE_NAME, COLUMN_NAME
  5             FROM USER_IND_COLUMNS
  6            WHERE TABLE_NAME IN ('TAB_XN_PRESMS', 'TAB_XN_PRESMS_DETAIL'))
  7            ORDER BY table_name,NUM_DISTINCT DESC;
 
TABLE_NAME                     COLUMN_NAME                    NUM_DISTINCT
------------------------------ ------------------------------ ------------
TAB_XN_PRESMS                  PRE_ID                              1999270
TAB_XN_PRESMS                  PRE_TIME                            1342594
TAB_XN_PRESMS                  EMPLOYEE_ID                           10676
TAB_XN_PRESMS                  COMPANY_ID                             3136
TAB_XN_PRESMS                  SEND_TYPE                                10
TAB_XN_PRESMS_DETAIL           DETAIL_ID                           3863184
TAB_XN_PRESMS_DETAIL           PRE_ID                              1996872
TAB_XN_PRESMS_DETAIL           SEND_TIME                            437526
 
8 rows selected
</pre>
<p>通过这些信息可以得出：<br />
1)统计信息是最新收集过的<br />
2)因为有多个单列index，数据库为了使得cost最小，可能选择了不合适的index(IDX_XN_PRESMS_2[EMPLOYEE_ID]/IDX_XN_PRESMS_1[COMPANY_ID]),使得出现AND-EQUAL，从而逻辑读偏高。对于这个sql，应该使用唯一度比较高的IDX_XN_PRESMS_3[PRE_TIME]<br />
3)也可以通过修改index，实现程序高效，但是考虑到会影响启动程序，在没有十足的把握之前遵守hint优先原则<br />
<br />
<strong>5.增加hint提示</strong></p>
<pre class="brush: sql; title: ; notranslate">SQL&gt; SELECT /*+ index(TABXNPRESM0_ IDX_XN_PRESMS_3) */
  2  COUNT(TABXNPRESM1_.DETAIL_ID) AS X0_0_
  3    FROM QXTDEV1.TAB_XN_PRESMS TABXNPRESM0_, QXTDEV1.TAB_XN_PRESMS_DETAIL TABXNPRESM1_
  4  WHERE  (TABXNPRESM0_.COMPANY_ID = 346240)
  5     AND (TABXNPRESM0_.EMPLOYEE_ID = 0)
  6     AND (TABXNPRESM0_.PRE_TIME &gt;= TO_DATE('2011/12/25', 'yyyy/mm/dd'))
  7     AND (TABXNPRESM0_.PRE_TIME &lt; TO_DATE('2011/12/26', 'yyyy/mm/dd') + 1)
  8     AND ((TABXNPRESM0_.SEND_TYPE = 1) OR (TABXNPRESM0_.SEND_TYPE = 0))
  9     AND ((TABXNPRESM1_.RESULT = -1) OR (TABXNPRESM1_.RESULT = 0))
 10     AND (TABXNPRESM0_.PRE_ID = TABXNPRESM1_.PRE_ID);

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=641 Card=1 Bytes=40)
   1    0   SORT (AGGREGATE)
   2    1     TABLE ACCESS (BY INDEX ROWID) OF 'TAB_XN_PRESMS_DETAIL'(Cost=3 Card=2 Bytes=30)
   3    2       NESTED LOOPS (Cost=641 Card=1 Bytes=40)
   4    3         TABLE ACCESS (BY INDEX ROWID) OF 'TAB_XN_PRESMS' (Cost=638 Card=1 Bytes=25)
   5    4           INDEX (RANGE SCAN) OF 'IDX_XN_PRESMS_3' (NON-UNIQUE) (Cost=63 Card=22286)
   6    3         INDEX (RANGE SCAN) OF 'IDX_XN_PRESMS_DETAIL' (NON-UNIQUE) (Cost=2 Card=2)



Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
       1422  consistent gets
          0  physical reads
          0  redo size
        375  bytes sent via SQL*Net to client
        503  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          1  rows processed</pre>
<p>从这里可以看出，程序的逻辑读下降了很多(从272188下降到1422)，得到了优化效果，提高了程序执行效率<br />
结合上篇:<a href="//www.xifenfei.com/1531.html" target="_blank">BITMAP CONVERSION FROM ROWIDS</a>,总结一个经验，如果同时使用到了一个表的多个index，效率一般情况下不会太高。同时也给各位提个醒，index并非越多越好，有时候会适得其反(建立index时需要考虑情况)</p>
<div id="crp_related"><ul><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/hint%e6%8c%87%e5%ae%9aindex%e7%9a%84%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3.html" rel="bookmark" class="crp_title">hint指定index的深入理解</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/04/%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e4%b8%ad%e5%b8%b8%e8%a7%81index%e8%ae%bf%e9%97%ae%e6%96%b9%e5%bc%8f.html" rel="bookmark" class="crp_title">执行计划中常见index访问方式</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/07/select-maxamina-from-table%e4%bc%98%e5%8c%96.html" rel="bookmark" class="crp_title">select max(id),min(id) from table优化</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/09/oracle%e7%9b%b4%e6%96%b9%e5%9b%be%e7%90%86%e8%a7%a3%e4%b8%8e%e5%ae%9e%e9%aa%8c.html" rel="bookmark" class="crp_title">Oracle直方图理解与实验</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2014/03/%e5%90%abis-null-sql%e8%af%ad%e5%8f%a5%e4%bc%98%e5%8c%96.html" rel="bookmark" class="crp_title">含is null sql语句优化</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/06/autotrace%e6%98%be%e7%a4%bastatistics%e5%be%88%e5%a4%9a%e4%bf%a1%e6%81%af%e4%b8%ba0.html" rel="bookmark" class="crp_title">autotrace显示Statistics很多信息为0</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2012/12/%e5%88%9b%e5%bb%ba%e6%94%af%e6%8c%81null-index.html" rel="bookmark" class="crp_title">创建包含null值index</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2013/08/oracle-12c-partial-globallocal-indexes-for-partitioned-tables.html" rel="bookmark" class="crp_title">ORACLE 12C Partial Global/Local Indexes for Partitioned Tables</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2014/10/11g%e4%b8%ad-connect-by-%e8%af%ad%e5%8f%a5%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e6%94%b9%e5%8f%98.html" rel="bookmark" class="crp_title">11g中 connect by 语句执行计划改变</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2015/05/oracle-12c-table-access-by-index-rowid-batched.html" rel="bookmark" class="crp_title">Oracle 12C TABLE ACCESS BY INDEX ROWID BATCHED</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2014/04/oracle-12c-in-memory%e5%8a%9f%e8%83%bd%e6%b5%8b%e8%af%95.html" rel="bookmark" class="crp_title">ORACLE 12C In-Memory功能性能测试</a></li><li style="list-style-type:decimal;font-size:11px;" ><a href="https://www.xifenfei.com/2011/09/10g%e6%96%b0%e5%a2%9e%e5%88%97%e6%96%b9%e5%bc%8f%e6%8c%87%e5%ae%9ahint.html" rel="bookmark" class="crp_title">10g新增列方式指定HINT</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>https://www.xifenfei.com/2011/12/%e8%ae%b0%e4%b8%80%e6%ac%a1%e5%90%aband-equal%e6%89%a7%e8%a1%8c%e8%ae%a1%e5%88%92%e8%b0%83%e4%bc%98.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
