oracle 用于避免重复行插入的SQL插入查询

c3frrgcw  于 2022-11-03  发布在  Oracle
关注(0)|答案(3)|浏览(193)

I am using the following SQL insert statement to insert values into a table MY_DATA , but here I want to add a check if the row already exists, based on data in column CREATED_AT .

INSERT INTO MY_DATA (SITE_ID, USER_NAME, USER_NO, CREATED_AT) 
VALUES (:siteId, :userName, :userNo, :createdAt)

Here if I try to insert the row with same value present in CREATED_AT column in the table it should not get inserted.
Using Oracle SQL developer for Database.
Please help I am new here.

edqdpe6u

edqdpe6u1#

使用MERGE陈述式:

MERGE INTO MY_DATA dst
USING DUAL
ON (dst.created_at = :created_at)
WHEN NOT MATCHED THEN
 INSERT (SITE_ID, USER_NAME, USER_NO, CREATED_AT)
 VALUES (:siteId, :userName, :userNo, :createdAt);

您可以建立索引,以防止使用相同的CREATED_AT值进行多次插入:

CREATE UNIQUE INDEX my_data__created_at__u ON my_data (created_at);

如果有,则可以在PL/SQL语句中使用查询并捕获异常错误(然后忽略它、报告它或对它执行任何需要的操作):

BEGIN
  INSERT INTO MY_DATA (SITE_ID, USER_NAME, USER_NO, CREATED_AT) 
  VALUES (:siteId, :userName, :userNo, :createdAt);
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    -- Handle the exception
    NULL;
END;
/
l5tcr1uw

l5tcr1uw2#

我认为您只需要在表的CREATE_AT列上创建一个UNIQUE INDEX-

CREATE UNIQUE INDEX idx_unq_created_at
ON MY_DATA (created_at);

在此之后,您不需要在查询中做任何事情。该索引将确保不会向表中的created_at列插入重复值。

i7uaboj4

i7uaboj43#

一个选项是使用合并,例如

merge into my_data a
  using (select :siteId    site_id, 
                :userName  user_name, 
                :userNo    user_no, 
                :createdAt created_at
         from dual
        ) b
on (a.created_at = b.created_At)
when not matched then 
  insert (site_id, user_name, user_no, created_at)
  values (b.site_Id, b.user_Name, b.user_No, b.created_At);

相关问题