How to use if exists- if not exists in PL/SQL?

前端 未结 3 1244
情话喂你
情话喂你 2021-01-27 05:47

I am trying to convert if exists statement from SQL-Server to PL/SQL but having an error.

I am trying to check if NAME_1 doesn\'t exist in my table_1<

3条回答
  •  伪装坚强ぢ
    2021-01-27 06:26

    Your code is mostly good, but you would have to modify it either like this:

    DECLARE
    l_count NUMBER;
    l_count_2 NUMBER;
    BEGIN
    select count(*) into l_count from table_1 where name='NAME_1';
    IF l_count = 0  then
        BEGIN 
            select count(*) into l_count_2 FROM dba_tab_cols  WHERE TABLE_NAME = 'table_1' AND COLUMN_NAME='NAME_2';
    
            IF l_count_2 > 0 THEN        
              sql_cnt :=  'INSERT INTO table_1 (xycolumn1, xycolumn2, xycolumn3) VALUES (''value1'', ''select max(column) from table_2'', ''20'')';          
            ELSE             
               sql_cnt := 'INSERT INTO table_1 (xycolumn1, xycolumn2) VALUES (''value1'', ''select max(column) from table_2'')';
            END IF;                    
           BEGIN
             EXECUTE IMMEDIATE sql_cnt ;
           END;
        END;
    END IF;       
    END;      
    

    or like this:

    DECLARE
    l_count NUMBER;
    l_count_2 NUMBER;
    BEGIN
    select count(*) into l_count from table_1 where name='NAME_1';
    IF l_count = 0  then
        BEGIN 
            select count(*) into l_count_2 FROM dba_tab_cols  WHERE TABLE_NAME = 'table_1' AND COLUMN_NAME='NAME_2';
    
            IF l_count_2 > 0 THEN        
              INSERT INTO table_1 (xycolumn1, xycolumn2, xycolumn3) VALUES ('value1', 'select max(column) from table_2', '20' );          
            ELSE             
              INSERT INTO table_1 (xycolumn1, xycolumn2) VALUES ('value1', 'select max(column) from table_2');
            END IF;   
        END;
    END IF;       
    END;      
    

    The first option is using the correct Oracle spelling for string creations and dynamic SQL and the second option is avoiding dynamic SQL altogether by executing INSERT on the spot (the option I prefer).

    EDIT : The error you got was because you did not encapsulate your INSERT inside a string. That is what I changed for you in my first option when I mentioned correct Oracle spelling for string creations and dynamic SQL.

    I hope I helped!

提交回复
热议问题