【问题标题】:check duplicate value before insert in oracle query without using trigger在不使用触发器的情况下插入 oracle 查询之前检查重复值
【发布时间】:2013-04-07 22:46:50
【问题描述】:

我需要在插入查询检查重复任何字段,如名字,如果此表中不存在,则插入新行并返回当前插入的 id 否则 如果表中存在名字,则返回零作为重复

不使用触发器、函数和过程

【问题讨论】:

  • 您说“返回”,但随后您排除了任何程序化解决方案。那么你到底想做什么?

标签: oracle oracle10g oracle11g


【解决方案1】:

没有“插入查询”之类的东西。

实现此类要求的正常方法是使用数据完整性约束:

alter table your_table 
    add constraint your_table_uk unique (first_name)
/

如果您尝试插入重复记录,这将引发任何异常。

获取当前插入的ID:

insert into your_table (id, first_name)
    values (your_seq.nextval, 'SAM-I-AM')
    returning id
/

您说您不想使用函数或过程,但如果提交的 first_name 是重复的,则返回 0 的唯一方法是编程:

create or replace function new_record (p_name your_table.first_name%type)
    return your_table.id%type
is
    return_value your_table.id%type;
begin
    begin
        insert into your_table (id, first_name)
            values (your_seq.nextval, p_first_name)
        returning id into return_value;
    exception
        when dup_val_on_index then
             return_value := 0;
    end;
    return return_value;
end;

【讨论】:

  • 如果我想将插入语句作为参数传递给该函数并在函数中执行并返回值该怎么办
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2016-03-31
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多