如果“不存在”插入失败,并显示“如果不存在”语句的“未知”命令错误

时间:2015-11-18 05:02:40

标签: sql oracle

我在Oracle Command下面插入一行但在此之前我应该​​检查表中是否存在该行,如果存在则不执行任何操作。

IF NOT EXISTS(SELECT * FROM table1 WHERE Value1 ='Value 1' AND Value2='Value 2' AND Value3='Value 3' AND Value4='Value 4')
BEGIN 
INSERT INTO table1
(
  Value1,
  Value2,
  Value3,
  Value4,
  Value5
)
VALUES
(
  'Value 1',
  'Value 2',
  'Value 3',
  'Value 4',
  'Value 5'
)
END;  

我觉得上面的陈述应该保持良好但是抛出

  

错误从第7行开始:命令中的错误 - IF NOT EXISTS(SELECT * FROM   table1 WHERE Value1 ='Value 1'AND   Value2 ='Value 2'AND Value3 ='Value 3'AND   Value4 ='Value 4')错误报告 - 未知命令

抛出的错误在这里挖掘更多关于这个问题并没有多大帮助,而且是新手。希望能找到一些帮助。

3 个答案:

答案 0 :(得分:2)

我经常使用MERGE来解决这类问题。它是纯SQL,简单明了。在您的示例中,它将是这样的:

MERGE table1 T1
USING (SELECT 'Value 1' Value1, 'Value 2' Value2, 'Value 3' Value3, 'Value 4' Value4 FROM DUAL) T2
ON (T1.Value1 = T2.Value1
AND T1.Value2 = T2.Value2
AND T1.Value3 = T2.Value3
AND T1.Value4 = T2.Value4)
WHEN NOT MATCHED THEN
INSERT VALUES (T2.Value1, T2.Value2, T2.Value3, T2.Value4);

答案 1 :(得分:2)

最简单的方法(不是最有效的方法)就是做

之类的事情
DECLARE
  l_cnt pls_integer;
BEGIN
  SELECT COUNT(*)
    INTO l_cnt
    FROM table_name
   WHERE col1 = 'value1'
     AND col2 = 'value2'
     ...

  IF( l_cnt = 0 )
  THEN
    <<your insert>>
  END IF;
END;

您可以执行insert,捕获异常并忽略它(我假设有一个唯一的约束可以防止重复的行,否则您将遇到严重的竞争条件,无论您如何实现检查)

BEGIN
  <<your insert>>
EXCEPTION
  WHEN dup_val_on_index
  THEN
    NULL; -- Ignore the exception, we don't have to insert the row
END;

或者你可以做merge。假设您使用10g,WHEN MATCHED子句将成为可选

MERGE INTO table_name dest
  USING( SELECT 'value 1' col1, 
                'value 2' col2,
                'value 3' col3,
                'value 4' col4
           FROM dual ) src
     ON( src.col1 = dest.col1 and
         src.col2 = dest.col2 and
         src.col3 = dest.col3 and
         src.col4 = dest.col4 )
 WHEN NOT MATCHED THEN
   INSERT( col1, col2, col3, col4 )
     VALUES( src.col1, src.col2, src.col3, src.col4 );

或者您可以insert

INSERT INTO table_name( col1, col2, col3, col4 )
  SELECT 'value1', 'value2', 'value3', 'value4'
    FROM dual
   WHERE NOT EXISTS( SELECT 1
                       FROM table_name
                      WHERE col1 = 'value1' 
                        AND col2 = 'value2'
                        AND col3 = 'value3'
                        AND col4 = 'value4' );

答案 2 :(得分:1)

这有点像黑客,但我试图想办法在Oracle中使用merge语句,但不知道如何将“if not exists”转移到null:< / p>

INSERT INTO table1
(Value1, Value2, Value3, Value4, Value5)
with cte as (
  select
    'Value 1' as v1, 'Value 2' as v2, 'Value 3' as v3,
    'Value 4' as v4, 'Value 5' as v5
  from dual
)
select *
from cte
where not exists (
  select null
  from table1
  where
    Value1 = cte.v1 and
    Value2 = cte.v2 and
    Value3 = cte.v3 and
    Value4 = cte.v4 and
    Value5 = cte.v5
)