就像标题所说的那样。我在if语句中有一个SQL语句(Oracle 9),其值为true。从我记得这样的声明将做SQL Server的预期。在这种情况下,我做错了什么?
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target')
或者更好的是,确保我不插入已存在的数据的适当策略是什么。写入的代码总是插入。这显然不是我想要的,因为这一行已经存在。
当此代码运行时,我收到以下控制台消息。
Error starting at line 1 in command:
IF (SELECT COUNT(*) FROM CUSTOMER_LIST WHERE CUSTOMER='Target')=0 THEN
Error report:
Unknown Command
1 rows inserted.
答案 0 :(得分:6)
问题似乎是你正在给PL / SQL预期直接SQL。要么直截了当地说SQL:
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER)
SELECT CUSTOMER_ID_SEQ.nextval, 'Target' FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM CUSTOMER_LIST WHERE CUSTOMER = 'Target')
或者更改周围的上下文,以便Oracle期望PL / SQL。这取决于你如何传递这些代码;但一种可能的方法是将其包裹在BEGIN ... END
块中。
此外,您不能将查询用作PL / SQL中的表达式;如果你去PL / SQL路线,你需要将结果存储在某个地方,例如变量。总而言之,你可能有这个:
DECLARE
v_customer_exists INTEGER;
BEGIN
SELECT COUNT(*) INTO v_customer_exists FROM CUSTOMER_LIST WHERE CUSTOMER='Target';
IF v_customer_exists = 0 THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target');
END IF;
END;
/
答案 1 :(得分:2)
DECLARE
v_count number;
BEGIN
SELECT COUNT(*) INTO v_count FROM CUSTOMER_LIST WHERE CUSTOMER='Target';
IF v_count = 0 THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target');
END IF;
END;
答案 2 :(得分:1)
尝试这样的方法来检查是否从选择中返回了任何行。当没有从select:
返回元组时,NOT EXISTS返回trueIF NOT EXISTS (SELECT * FROM CUSTOMER_LIST WHERE CUSTOMER='Target') THEN
INSERT INTO CUSTOMER_LIST (CUSTOMER_ID, CUSTOMER) VALUES
(CUSTOMER_ID_SEQ.nextval, 'Target')