[英]How to loop over records and then search into another table and if not found then insert it after fetching records from another table in oracle?
你可以試試這個:
INSERT INTO table_2
SELECT table_1.id, table_1.name, table_1.gender, table_1.age, table_3.phone_num
FROM table_1
INNER JOIN table_3 ON table_1.id = table_3.id
WHERE table_1.id NOT IN (SELECT id FROM table_2);
您可以使用MERGE
語句來避免兩次訪問Table2
:
MERGE INTO table2 dst
USING (
SELECT t1.*, t3.phone_num
FROM table1 t1
LEFT OUTER JOIN table3 t3
ON (t1.id = t3.id)
) src
ON (src.id = dst.id)
WHEN NOT MATCHED THEN
INSERT (id, name, gender, age, phone_num)
VALUES (src.id, src.name, src.gender, src.age, src.phone_num);
如果您還想更新現有行,則可以在同一語句中執行此操作:
MERGE INTO table2 dst
USING (
SELECT t1.*, t3.phone_num
FROM table1 t1
LEFT OUTER JOIN table3 t3
ON (t1.id = t3.id)
) src
ON (src.id = dst.id)
WHEN MATCHED THEN
UPDATE
SET name = src.name,
gender = src.gender,
age = src.age,
phone_num = src.phone_num
WHEN NOT MATCHED THEN
INSERT (id, name, gender, age, phone_num)
VALUES (src.id, src.name, src.gender, src.age, src.phone_num);
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.