代码之家  ›  专栏  ›  技术社区  ›  Leonardo Alves Machado Vivek Kumar

仅当表存在时才删除行

  •  0
  • Leonardo Alves Machado Vivek Kumar  · 技术社区  · 6 年前

    如果以前创建了表,我需要在数据库上运行delete语句。

    00942. 00000 - "table or view does not exist" .

    举个例子:

    我想运行这样的程序:

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

    如果没有泛型语句,我希望有一个将运行的Oracle数据库

    2 回复  |  直到 6 年前
        1
  •  5
  •   Jon Theriault    6 年前

    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;
    
        2
  •  2
  •   Jeffrey Kemp    6 年前

    最简单的方法是捕获并忽略“table not found”异常:

    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;
    /