首页 > 解决方案 > 仅当表存在时才删除行

问题描述

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

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

一个例子:

我想运行这样的东西:

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

如果没有通用语句,我想要一个适用于 Oracle 数据库的语句

标签: sqloracle

解决方案


这是甲骨文的一个。这假定当前用户拥有该表。如果您要更新其他人的表,则需要将 user_tables 替换为 dba_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;

推荐阅读