sql - insert if not exists

后端 未结 4 1712
别那么骄傲
别那么骄傲 2021-01-13 08:44

I am having trouble with a sql query. I need to insert a row if the same row does not exist already. This is what I have so far:

DECLARE
BEGIN
   FOR FOLDE         


        
相关标签:
4条回答
  • 2021-01-13 08:59

    Do it all in SQL rather than context switching into 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);
    
    0 讨论(0)
  • 2021-01-13 09:03

    A better (Oracle specific?) solution may be the MERGE statement.

    See here for a nice explanation, with examples:

    http://www.oracle-base.com/articles/10g/MergeEnhancements10g.php

    Hope that helps.

    0 讨论(0)
  • 2021-01-13 09:04

    You forgot the THEN

    IF condition THEN  
       ...
    ELSE
        ...
    END IF;
    
    0 讨论(0)
  • 2021-01-13 09:15
    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;
    
    0 讨论(0)
提交回复
热议问题