DROP和CREATE索引同时进行

时间:2014-12-05 14:32:29

标签: sql oracle oracle11g

我们有表所有者名称和索引所有者名称不匹配。我们需要删除索引以及与之关联的约束,并在特定模式中重新创建相同的索引以匹配索引所有者和表所有者名称。我们对每个索引的列数不同,从1到4不等。 我需要创建一个同时删除n重新创建的过程。

declare
total number(10);
table_name varchar2(255);
index_name varchar2(255);
column_name varchar2(255);
begin
select  a.table_name, a.index_name,count(a.column_name) into table_name, index_name,total
from all_ind_columns a, all_indexes b where a.index_name = b.index_name
and b.table_owner = 'SIM'and b.owner like 'TIM'
group by a.table_name,a.index_name
order by a.table_name,a.index_name,count(a.column_name);
select c.column_name into column_name from all_ind_columns c,all_indexes d 
where c.index_name=d.index_name 
and d.table_owner='SIM' and d.owner like 'TIM';
for i in (select  a.table_name, a.index_name,count(a.column_name) from all_ind_columns a, all_indexes b where a.index_name = b.index_name
and b.table_owner = 'SIM'and b.owner like 'TIM'
group by a.table_name,a.index_name
order by a.table_name,a.index_name,count(a.column_name))
loop
If i.count(a.column_name)=1 then
DBMS_OUTPUT.PUT_LINE ('Create index'||index_name|| 'on' ||table_name||'('||Column_name||')');
else total>=2
then
DBMS_OUTPUT.PUT_LINE ('Create index'||index_name|| 'on' ||table_name||'('||Column_name,Column_name||')');
end if;
end loop;
end;

1 个答案:

答案 0 :(得分:1)

DBMS_METADATA是重新生成对象DDL的官方方法。它通常比手动创建DDL语句更好。创建索引有数百种选项,DBMS_METADATA.GET_DDL是确保准确重新创建对象的唯一方法。

declare
    v_index_ddl clob;
begin
    for indexes_in_wrong_schema in
    (
        select table_name, index_name
        from all_indexes
        where table_owner = 'SIM' and owner like 'TIM'
    ) loop
        v_index_ddl := dbms_metadata.get_ddl('INDEX', 
            indexes_in_wrong_schema.index_name, 'TIM');
        --Or replace these with "execute immediate" to run instead of print.
        dbms_output.put_line('drop index TIM.'||
            indexes_in_wrong_schema.index_name);
        dbms_output.put_line(replace(v_index_ddl, '"TIM"', '"SIM"'));
    end loop;
end;
/

<强>权限

DBMS_METADATA要求您拥有SELECT_CATALOG_ROLE或正在作为架构所有者执行。询问DBA或其他特权用户是否可以授予您该角色。或者将上面的PL / SQL块转换为函数,在所有者的架构上安装该函数,然后grant execute on new_function to your_user;