我遇到了一个SQL查询问题。如果已经存在相同的行,我需要插入一行。这就是我到目前为止所做的:
DECLARE
BEGIN
FOR FOLDER_ROW IN (SELECT FOLDERID, USERID FROM DATA1.FOLDERS)
LOOP
IF NOT EXISTS (SELECT * FROM DATA1.FOLDER_USER WHERE FOLDER_ID = FOLDER_ROW.FOLDERID AND USER_ID = FOLDER_ROW.USERID)
INSERT INTO DATA1.FOLDER_USER (FOLDER_ID, USER_ID) VALUES (FOLDER_ROW.FOLDERID, FOLDER_ROW.USERID);
END LOOP;
COMMIT;
END;
我不太熟悉sql特别是不存在的语法所以当我执行时我得到以下错误:
ORA-06550:第37行,第11栏:PLS-00103:遇到符号 期待以下之一时“插入”:
然后和或
符号“then”代替“INSERT”继续。
ORA-06550: line 38, column 10: PLS-00103: Encountered the symbol "LOOP" when expecting one of the following: if ORA-06550: line 40, column 5: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: end not pragma final instantiable order overriding static member constructor map
答案 0 :(得分:12)
在SQL中完成所有操作而不是上下文切换到PL / SQL:
INSERT INTO DATA1.FOLDERS
(folder_id,
user_id)
SELECT f1.folder_id,
f1.user_id
FROM DATA1.FOLDERS f1
WHERE NOT EXISTS (SELECT 1
FROM DATA1.FOLDERS f2
WHERE f1.folder_id = f2.folder_id
AND f1.user_id = f2.user_id);
答案 1 :(得分:2)
更好的(特定于Oracle的?)解决方案可能是MERGE语句。
请参阅此处以获得一个很好的解释,例如:
http://www.oracle-base.com/articles/10g/MergeEnhancements10g.php
希望有所帮助。
答案 2 :(得分:1)
您忘记了那么
IF condition THEN
...
ELSE
...
END IF;
答案 3 :(得分:0)
DECLARE
N_COUNTS NUMBER;
BEGIN
select count(ID) into N_COUNTS from TABLE_NAME where ID = 1;
IF N_COUNTS=0 THEN
INSERT QUERY....
ELSE
UPDATE QUERY....
END IF;
END;