仅在表存在时删除行

时间:2018-11-12 13:18:57

标签: sql oracle

如果先前已创建表,则需要在数据库上运行delete语句。

问题是-我不能只运行delete语句,因为该产品不在每个客户端的生产环境中-因此,他们没有我要在其中运行delete语句的表,最终错误00942. 00000 - "table or view does not exist"

一个例子:

我想运行以下内容:

IF EXISTS (TABLE TB_FIELD)
    DELETE FROM TB_FIELD WHERE ID = '213';

如果没有通用语句,我希望可以在Oracle数据库中运行该语句

2 个答案:

答案 0 :(得分:5)

这是Oracle的一个。假设当前用户拥有该表。如果要更新其他人的表,则需要用dba_tables换出user_tables。

declare
    table_name_l    user_tables.table_name%type;
begin
    select table_name into table_name_l from user_tables where table_name = 'TB_FIELD';
    -- if we didn't raise an exception the table must exist 
    execute immediate 'delete from tb_field where id = :1' using '213';

    exception 
        when no_data_found then 
            -- do nothing - table doesn't exist
            null;
end;

答案 1 :(得分:2)

最简单的方法是捕获并忽略“找不到表”异常:

declare
  l_id number := 12345;
begin
  execute immediate 'delete tb_field where id=:1' using l_id;
exception
  when others then
    if sqlcode != -942 /*table or view does not exist*/ then
      raise;
    end if;
end;
/
相关问题