sql - Oracle PLS-00103 错误。您如何检查现有记录并根据该条件进行更新或插入?

标签 sql oracle plsql upsert ora-00900

我需要通过 SELECT 语句检查表中是否存在记录。如果记录存在,则进行更新,否则在表上创建记录。我正在尝试,但遇到 PLS-00103 错误。

这些是我在 DBVisaulzier 中运行代码时遇到的错误:

18:00:09  [DECLARE - 0 row(s), 0.000 secs]  [Error Code: 6550, SQL State: 65000]  ORA-06550: line 2, column 12:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

:= . ( @ % ; not null range default character
18:00:09  [BEGIN - 0 row(s), 0.000 secs]  [Error Code: 6550, SQL State: 65000]  
ORA-06550: line 2, column 97:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

;
18:00:09  [IF - 0 row(s), 0.000 secs]  [Error Code: 900, SQL State: 42000]  ORA-00900: invalid SQL statement
18:00:09  [ELSE - 0 row(s), 0.000 secs]  [Error Code: 900, SQL State: 42000]   
ORA-00900: invalid SQL statement
18:00:09  [END - 0 row(s), 0.000 secs]  [Error Code: 900, SQL State: 42000]  ORA-00900: invalid SQL statement
18:00:09  [END - 0 row(s), 0.000 secs]  [Error Code: 900, SQL State: 42000]  ORA-00900: invalid SQL statement
... 6 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec  [0 successful, 0 warnings, 6 errors]

以下是我的代码:

DECLARE a NUMBER;

BEGIN

  SELECT 1 
    INTO a 
    FROM FREC_EMAIL t
   WHERE t.FranchiseNo = '208254846' 
     AND t.ReportID = 1 
     AND t.id = 165;

  IF a=1 THEN

       UPDATE FREC_EMAIL
          SET email = 'blah@foo.com'
        WHERE FranchiseNo = '208254846' 
          AND ReportID = 1 
          AND ID = 165;

    ELSE

        INSERT INTO FREC_EMAIL
          (FranchiseNo, Email, ReportID)
         VALUES
           ('208254846', 'blah@foo.com', 1);

    END IF;
END;

最佳答案

我们应该尽可能使用 SQL,除非绝对必要,否则避免使用 Pl/SQL。 SQL 语句执行得更快,它们通常需要更少的输入,并且更容易正确。

自 9i 以来,Oracle 提供了 MERGE,即执行“upsert”语句的单个 SQL 语句。

MERGE INTO frec_email t
USING (SELECT  'blah@foo.com' as email
                ,  '208254846' as FranchiseNo
                , 1 as ReportID
                , 165 as ID 
       FROM dual ) s
ON (s.ID = t.ID)
WHEN MATCHED THEN
     UPDATE SET t.email = s.email
WHEN NOT MATCHED THEN
    INSERT (t.FranchiseNo, t.Email, t.ReportID)
    VALUES  (s.FranchiseNo, s.Email, s.ReportID)
/

关于sql - Oracle PLS-00103 错误。您如何检查现有记录并根据该条件进行更新或插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1463119/

相关文章:

mysql - 写入 UPDATE 语句时出现重复主键错误

oracle - ColdFusion:获取 ORA-28000:运行 cfschedule 时帐户被锁定

c# - 无法在 Oracle 中使用 Fluent Nhibernate 获取间隔

oracle - Oracle pl/sql 电子邮件中的特殊字符

创建自动编号的 Oracle 触发器

mysql - 我什么时候应该对列使用 UNSIGNED 属性?

MySQL 版本 5.5.37 : Dropping tables older than 30 days using CURSOR

MySQL - 带有 GROUP BY 的条件 COUNT

oracle - PL/SQL 如何使用子查询和参数进行 INSERT

Oracle Deref 函数 : wrong numer or type of arguments