Oracle學習筆記:判斷表是否存在函數 is_table_exists


在 Oracle 中可以利用系統表 user_tablesall_talbes 判斷表是否存在,但有時在存儲過程中確認表是否存在並不方便,因此有必要封裝一個函數,進行調用。

下面是函數的內容:

-- 判斷表是否存在
create or replace function temp_is_table_exists(is_table_name varchar2, is_owner_name varchar2 default null)
	return boolean is

	vcproc_name varchar2(100) := 'TEMP_IS_TABLE_EXISTS';
	vncount number(10);
	vnerr_code number;
	vcerr_text varchar2(2000);
	
	vcowner_name varchar2(1000);
	vctable_name varchar2(1000);
	
begin
	vncount := 0;
	
	vcowner_name := is_owner_name;
	vctable_name := is_table_name;
	
	if vcowner_name is null then 
		select count(1) into vncount
		from user_tables
		where table_name = upper(vctable_name);
	else
		select count(1) into vncount
		from all_tables
		where owner = upper(vcowner_name)
		and table_name = upper(vctable_name);
	end if;
	
	if vncount > 0 then 
		return true;
	else 
		return false;
	end if;

exception
	when others then 
		vnerr_code := sqlcode;
		vcerr_text := sqlerrm;
		-- 記錄異常以備查
		pro_cwh_test(vcproc_name, vctable_name, vnerr_code, vcerr_text);
		rollback;
		commit;
end temp_is_table_exists;

其中,入參為:表名 + 用戶名,用戶名可缺省。

最后面 exception 為異常拋出部分,記錄進日志表。

-- 異常拋出
exception when others then 
-- sqlcode 異常編碼  -12170
-- sqlerrm 信號字符串  ORA-12170: TNS:Connect timeout occurred

經測試驗證,return 為布爾型的函數不能夠直接通過 select 執行。

神奇!!!

select is_table_exists('temp_cwh_city') from dual;
-- 報錯

所以,該函數只能用於存儲過程中。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM