Oracle SQL : Retrieving non-existing values from IN clause

前端 未结 5 1519
孤独总比滥情好
孤独总比滥情好 2021-01-23 16:00

Having following query:

select table_name
from user_tables
where table_name in (\'A\',\'B\',\'C\',\'D\',\'E\',\'F\');

Assuming only user_tables

5条回答
  •  灰色年华
    2021-01-23 16:31

    Are you restricted to receiving those values as a comma delimited list?

    1. instead of creating a comma delimited list with the source values, populate an array (or a table).
    2. pass the array into a pl/sql procedure (or pull a cursor from the table).
    3. loop through the array(cursor) and use a dynamic cusror to select count(table_name) from user_tables where table_name = value_pulled.
    4. insert into table B when count(table_name) = 0.
    5. then you can select all from table B

      select * from tab1;
      ------------------
      A
      B
      C
      D 
      E
      F 
      
      Create or replace procedure proc1 as  
      
      cursor c is select col1 from tab1;
      r tab1.col1%type;
      i number;
      
      begin  
      
      open c;
      loop
        fetch c into r;
        exit when c%notfound; 
        select count(tname) into i from tab where tname = r;
          if i = 0 then 
            v_sql := 'insert into tab2 values ('''||r||''');
            execute immediate v_sql; 
            commit;
          end if; 
      end loop;
      close c;
      end proc1;
      
      select * from tab2;
      ------------------
      A
      D 
      E 
      

    if this is not a one-off, then having this proc on hand will be handy.

提交回复
热议问题