Wednesday, June 3, 2020

PL SQL Constraints with conditions


TABLE_NAME.category_Type ='ABC,DEF,GEF'


ANOTHER_TABLE.Value have ABC,DEF,GEF in different rows


I created a trigger to check each comma separated values should belong to ANOTHER_TABLE.

CREATE OR REPLACE  TRIGGER TRIGGER_NAME
 BEFORE  INSERT or UPDATE ON  TABLE_NAME
 REFERENCING OLD AS old    NEW AS new
FOR EACH ROW
BEGIN
DECLARE
  num_rows integer;
  dup_rows integer;
  temptype nvarchar2(100);
BEGIN
--  Check each comma separated values are from the ANOTHER_TABLE table where category ='Type'     
--  else throw error
select TO_CHAR( regexp_replace(TO_CHAR(:NEW.category_Type), '[[:space:]]*','')) into temptype from dual;

FOR i IN
   (SELECT trim(regexp_substr(temptype , '[^,]+', 1, LEVEL)) l
     FROM dual
       CONNECT BY LEVEL <= regexp_count(temptype , ',')+1
     )
   LOOP
 
SELECT
     count(1) into num_rows       
FROM   ANOTHER_TABLE where category ='Type' and value=i.l;

if(num_rows=0) then
      RAISE_APPLICATION_ERROR(-20000,'type did not match with expected ANOTHER_TABLE.value');
      end if;

    END LOOP;

  END;
END;

No comments:

Post a Comment