mercredi 18 septembre 2019

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

I am trying to convert if exists statement from sqlserver to PL/sql but having an error.

I am trying to check if NAME_1 doesn't exist in my table_1, if they don't exist then i am checking if COLUMN_NAME='NAME_2' exist in my table_1, if it exist then insert (NAME_1 and NAME_2) into my table_2. Thanks

My SQL :

    IF NOT (EXISTS (SELECT * from table_name_1 where name='NAME_1'))
BEGIN
        IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'table_1' AND COLUMN_NAME='NAME_2'))

            EXEC('insert into table_name_1 values (''value1'', (select max(column) from table_2), 20)');
        ELSE
            EXEC('insert into table_name_1 values (''value1'', (select max(column) from table_2))');
END

ORACLE:

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  VALUES ('value1', "select max(column) from table_2" , '20' );          
        ELSE             
            sql_cnt:= INSERT INTO table_1  VALUES ('value1', "select max(column) from table_2" );
        END IF;                    
       BEGIN
         EXECUTE IMMEDIATE sql_cnt ;
       END;
    END;
END IF;       
END;        

Aucun commentaire:

Enregistrer un commentaire