如果记录不存在,则在SQL中插入记录

时间:2014-03-03 06:53:25

标签: sql oracle insert duplicates

我想在SQL中插入记录,以便在条目组合存在的情况下,脚本不应继续使用insert语句。这是我到目前为止所做的:

insert into TABLE_TESTING(R_COMPONENT_ID,OPRID) 
select 1942,'Test' 
from  TABLE_TESTING 
where not exists 
    (select * 
     from TABLE_TESTING 
     where R_COMPONENT_ID='1942' 
       and oprid ='Test');

我的表名为:TABLE_TESTING 它有两列:R_COMPONENT_ID和OPRID

如果DB中已经存在记录为'1942'和'Test'的组合,那么我的脚本不应该执行插入操作,如果它存在,那么它应该将记录作为R_COMPONENT_ID和OPRID的组合插入。

请建议。 使用上面指定的查询,我在DB中添加了多个插入。请提出一些解决方案。

5 个答案:

答案 0 :(得分:3)

由于您不想更新现有行,因此您的方法基本上是正确的。您需要做的唯一更改是替换insert语句源中的from table_testing

insert into TABLE_TESTING (R_COMPONENT_ID,OPRID) 
select 1942,'Test' 
from  dual -- <<< this is the change
where not exists 
    (select * 
     from TABLE_TESTING 
     where R_COMPONENT_ID = 1942
       and oprid = 'Test');

当您使用from table_testing时,这意味着插入尝试在TABLE_TESTING中为每行插入一行。但您只想插入单个行。从DUAL中选择将实现这一目标。

正如其他人所指出的那样,您也可以使用MERGE语句,如果您需要插入的不仅仅是一行,那么这可能会更好一些。

merge into table_testing target
using 
(
    select 1942 as R_COMPONENT_ID, 'Test' as OPRID from dual
    union all 
    select 1943, 'Test2' from dual
) src
ON (src.r_component_id = target.r_component_id and src.oprid = target.oprid)
when not matched
then insert (r_component_id, oprid)
     values (src.r_component_id, src.oprid);

答案 1 :(得分:2)

试试这个

if not exists(Select * From TABLE_TESTING where R_COMPONENT_ID='1942' and OPRID='Test' )
begin
    insert into TABLE_TESTING(R_COMPONENT_ID,OPRID) values('1942','Test')
end

答案 2 :(得分:0)

您可以使用MERGE操作。

答案 3 :(得分:0)

insert into TABLE_TESTING  
select 1942,'Test' where 0<(
select count(1) from TABLE_TESTING 
where not exists(select 1 from TABLE_TESTING  where R_COMPONENT_ID=1942 and oprid ='Test'))

试试上面的代码。

答案 4 :(得分:0)

这是一个使用MERGE的skelton。我运行它,它工作正常。您可以根据自己的需要进一步调整。希望这有帮助!

DECLARE
BEGIN
   FOR CURTESTING IN (SELECT R_COMPONENT_ID, OPRID FROM TABLE_TESTING)
   LOOP
      MERGE INTO TABLE_TESTING
           USING DUAL
              ON (R_COMPONENT_ID = '1942' AND OPRID = 'Test')
      WHEN NOT MATCHED
      THEN
         INSERT     (PK, R_COMPONENT_ID, OPRID)
             VALUES (TEST_TABLE.NEXTVAL, '1942', 'Test');
   END LOOP;

   COMMIT;
END;