If Exists If Not Exists in Oracle

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

IF EXISTS IF NOT EXISTS IN ORACLE Author JP Vijaykumar Date Sept 14th 2012 In our application, I need to create a view,

if a private db_link exists. If the view exists, I need to grant select on the view to a role. Some schemas in our application do not have private db links. In such situation, I should do nothing and exit. This is my script to do the job. set serverout on size 1000000 timing on declare begin for c1 in ( select nvl((select 'create or replace view emp_grade as select * from emp_grade @'||db_link from user_db_links where username='VEEKSHA' and host='ORCL.world'), 'NULL') cmd from dual) loop begin dbms_output.put_line(c1.cmd); if (c1.cmd <> 'NULL') then execute immediate c1.cmd; end if; exception when others then dbms_output.put_line(sqlerrm); end; end loop; for c2 in ( select nvl((select 'grant select on '||view_name||' to dev_user' from user_views where view_name ='EMP_GRADE'),'NULL') cmd from dual) loop begin dbms_output.put_line(c2.cmd); if (c2.cmd <> 'NULL') then execute immediate c2.cmd; end if; exception when others then dbms_output.put_line(sqlerrm); end; end loop; end; / I further modified my procedure: ----------------------------------------------------------------------------------------set serverout on size 1000000 timing on declare begin for c1 in ( select nvl((select 'create or replace view emp_grade as select * from emp_grade

@'||db_link from user_db_links where username='VEEKSHA' and host='ORCL.world'), 'select null from dual') cmd from dual) loop begin dbms_output.put_line(c1.cmd); execute immediate c1.cmd; exception when others then dbms_output.put_line(sqlerrm); end; end loop; for c2 in ( select nvl((select 'grant select on '||view_name||' to dev_user' from user_views where view_name ='EMP_GRADE'),'select null from dual') cmd from dual) loop begin dbms_output.put_line(c2.cmd); execute immediate c2.cmd; exception when others then dbms_output.put_line(sqlerrm); end; end loop; end; / References: http://www.databasejournal.com/scripts/article.php/3822821/IF-EXISTSIF-NOT-EXIST S.htm http://www.databasejournal.com/scripts/article.php/3828731/Nulli-Secundus.htm

You might also like