一,業務場景:根據表名+某列的具體值+該列的數據類型_查詢出全部有關聯的表及列名sql
二 Oracle 存儲過程spa
總體代碼:code
create or replace PROCEDURE proc_hw(tab_name IN VARCHAR,--表名稱 col_value IN VARCHAR, --列值 col_type IN VARCHAR --數據類型 ) IS v_bcount number; out_tab_name VARCHAR2(50); col_name VARCHAR2(50); CURSOR cur_a IS select TABLE_NAME from user_tables WHERE TABLESPACE_NAME is not null AND TABLE_NAME!=tab_name ORDER BY TABLE_NAME ASC; -- 遊標1 CURSOR cur_b(ta_name VARCHAR) IS SELECT table_name, column_name, data_type FROM all_tab_cols WHERE table_name =ta_name AND data_type like '%'||col_type ||'%' AND owner='表空間的用戶名' ORDER BY data_type; -- 遊標2 BEGIN FOR a_cur IN cur_a LOOP FOR b_cur IN cur_b(a_cur.TABLE_NAME) LOOP execute immediate 'SELECT '||''''||a_cur.TABLE_NAME||''''|| ' FROM DUAL' into out_tab_name;--動態檢索sql execute immediate 'SELECT '||''''||b_cur.column_name||''''|| ' FROM DUAL' into col_name;--動態檢索sql execute immediate 'select count(*) from '||a_cur.TABLE_NAME || ' where "'|| b_cur.column_name||'" IS NOT NULL AND "'|| b_cur.column_name||'"='''||col_value||'''' into v_bcount;--動態檢索sql IF v_bcount>0 THEN DBMS_OUTPUT.PUT_LINE(tab_name||'-----'||col_value||'-------'||v_bcount||'------'||col_name||'------'||out_tab_name); end IF; END LOOP; END LOOP; END;
注:1.代碼中 ‘‘’’ 爲轉義單引號;io
2.此sql語句在Navicat12中編譯經過,Navicat11中編譯不經過編譯
三 調用 table
begin proc_hw('tableName','colValue','colDataType'); END;
四 分歧class
遊標1 在有時候不成立,select
CURSOR cur_a IS select TABLE_NAME from user_tables WHERE TABLESPACE_NAME is not null AND TABLE_NAME!=tab_name ORDER BY TABLE_NAME ASC; -- 遊標1
換成下面這種寫法sql語句
CURSOR cur_a IS select TABLE_NAME from dba_tables WHERE TABLESPACE_NAME='tablespace' AND TABLE_NAME!=tab_name ORDER BY TABLE_NAME ASC; -- 遊標1
改成上面的sql以後如果提示 視圖或表不存在,可執行下面的sql數據類型
grant select any dictionary to 用戶名;