Thursday, July 24, 2014

Oracle: how to remove duplicate constraints of 'CHECK' type


create or replace function get_search_condition(ownerr in varchar2, p_cons_name in varchar2) return varchar2 authid current_user
 is
   l_search_condition user_constraints.search_condition%type;
 begin
  select search_condition into l_search_condition from all_constraints where constraint_name = p_cons_name and owner = ownerr;
  return l_search_condition;
end;
/

--select 'ALTER TABLE ' || owner ||'.'|| table_name || ' DROP CONSTRAINT ' ||  regexp_replace(constraints, '^\w+; ', '') || ';' from (
  select owner, table_name, search_condition
  , listagg(constraint_name, '; ') within group (order by constraint_name) constraints
  from (
    select owner, table_name, regexp_replace(lower(get_search_condition(owner, constraint_name)), '\s+', ' ') search_condition, constraint_name
      from all_constraints where owner in (
      select owner from dba_tables where owner not in ('SYS', 'SYSTEM', 'APEX_040000', 'MDSYS', 'CTXSYS', 'FLOWS_FILES', 'OUTLN', 'XDB')
      ) and constraint_type = 'C' and search_condition IS NOT NULL
      order by table_name, constraint_name
  ) group by owner, table_name, search_condition having (count(constraint_name) > 1)
--)
;
drop function get_search_condition;

No comments:

Post a Comment