gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:13:57 24 4
gpt4 key购买 nike

我需要通过 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com