使用IF / ELSE语句插入

时间:2018-01-17 04:09:39

标签: sql oracle if-statement

如果我的问题不明确或我的查询不足以帮助我,我很抱歉。我有一个具有多个if / else语句的过程。我的目标是在if语句满足条件时插入一行,否则更进一步。像这样:

create or replace procedure abc.xyz
       ( i_name    varchar2
        ,number    number,
         sections       varchar2)
      ...
    max_date date;
    min_date   date;
     ...
    if(sum=0)
    insert into abc_table
    (id,name,number,sections,description,date,amount,price,source,latest_date)
     select user_seq.nextval,name,number,max_date,amount,0 
     ,'xyz',trunc(sysdate))
      from abc_table x
      where x.name=i_name
      and x.number=i_name
     and x.section=i_section;

    elseif (sum>0)
     insert into abc_table
     (id,name,number,sections,description,date,amount,price,source,latest_date)
     select user_seq.nextval,name,number,max_date,amount,0 
     ,'xyz',trunc(sysdate))
      from abc_table x
      where x.name=i_name
      and x.number=i_name;
      and x.section=i_section;

当我运行我的程序时,为了插入计算值,值是正确的但插入了很多行。如何防止多次插入并仅插入一行?

1 个答案:

答案 0 :(得分:0)

你做错了。

根据Oracle文档,使用VALUES关键字插入单个记录时Oracle INSERT语句的语法是:

INSERT INTO table
(column1, column2, ... column_n )
VALUES
(expression1, expression2, ... expression_n );

但是,使用SELECT语句插入多个记录时,Oracle INSERT语句的语法是:

INSERT INTO table
(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
[WHERE conditions];

参考:https://www.techonthenet.com/oracle/insert.php

来自我分享的链接: 如果您不想插入副本:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE NOT EXISTS (SELECT *
              FROM clients
              WHERE clients.client_id = 10345);