Pergunta

Preciso largar uma mesa e fazer uma nova. Se eu soltar a tabela e a tabela não existir, recebo um erro

Como posso verificar se a tabela existe?

Estou trabalhando no Oracle 11g

Desde já, obrigado.

Foi útil?

Solução

Você poderia fazer algo assim:

DECLARE v_exist PLS_INTEGER;
BEGIN

SELECT COUNT(*) INTO v_exist
FROM user_tables
WHERE table_name = 'YOURTABLEHERE';

IF v_exist = 1 THEN
    EXECUTE IMMEDIATE 'DROP TABLE YOURTABLEHERE';
END IF;

Outras dicas

DECLARE
  eTABLE_OR_VIEW_DOES_NOT_EXIST  EXCEPTION;
  PRAGMA EXCEPTION_INIT(eTABLE_OR_VIEW_DOES_NOT_EXIST, -942);
BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE SCHEMA.WHATEVER';
EXCEPTION
  WHEN eTABLE_OR_VIEW_DOES_NOT_EXIST THEN
    NULL;
END;

Compartilhe e curta.

algo como

select count(*) from user_tables 
where table_name= :table name

ou

select count(*) from dba_tables
where owner = :table owner
and table_name = :table name

ou uma alternativa pesada:

begin execute immediate 'drop table table_name'; 
exception when others then null; 
end;

Eu tenho usado o seguinte procedimento para cuidar disso:

create or replace procedure drop_table_if_exists ( p_table_name varchar2 )
is
  it_exist number;
begin
  select count(*) 
     into it_exists
     from user_tables
     where table_name = p_table_name
  ;
  if it_exists >= 1 then
    execute immediate 'drop table '||p_table_name;
  end if;
end;
/

exec drop_table_if_exists ( 'TABLE_TO_DROP' );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top