如何擷取Oracle share pool中沒有使用綁定變數的SQL

來源:互聯網
上載者:User

    ASKTOM網站提供了一個函數remove_constants,來檢查共用池中的SQL運行情況,處理思路是將查詢條件值變為一個通用標記,如:select * from t where object_id=1替換成select * from t where object_id=@ 。

SQL> drop table find_no_bind purge;
SQL> create table t as select * from dba_objects where 1=2;

--建立紀錄表
SQL> create table find_no_bind as select sql_text from v$sqlarea;
SQL> alter table find_no_bind add sql_text_copy varchar2(1000);

--建立替換函數,把預留位置替換成@
create or replace function 
SQL> remove_constants( p_query in varchar2 ) return varchar2
as
    l_query long;
    l_char  varchar2(1);
    l_in_quotes boolean default FALSE;
begin
    for i in 1 .. length( p_query )
    loop
        l_char := substr(p_query,i,1);
        if ( l_char = '''' and l_in_quotes )
        then
            l_in_quotes := FALSE;
        elsif ( l_char = '''' and NOT l_in_quotes )
        then
            l_in_quotes := TRUE;
            l_query := l_query || '''#';
        end if;
        if ( NOT l_in_quotes ) then
            l_query := l_query || l_char;
        end if;
    end loop;
    l_query := translate( l_query, '0123456789', '@@@@@@@@@@' );
    for i in 0 .. 8 loop
        l_query := replace( l_query, lpad('@',10-i,'@'), '@' );
        l_query := replace( l_query, lpad(' ',10-i,' '), ' ' );
    end loop;
    return upper(l_query);
end;
/

--先清一下share pool,正式環境不能這麼幹

SQL> alter system flush shared_pool;

SQL> begin
for i in 1..1000 loop
execute immediate 'select * from t where OBJECT_ID = '||i;
end loop;
end;
/

SQL> update find_no_bind set sql_text_copy = remove_constants(sql_text);

SQL> commit;

SQL> col sql_text_copy format a40
SQL> select sql_text_copy, count(*)
  2    from find_no_bind
  3   group by sql_text_copy
  4  having count(*) > 10;
SQL_TEXT_COPY                              COUNT(*)
---------------------------------------- ----------
SELECT * FROM T WHERE OBJECT_ID = @             1000

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.