Skip to Main Content

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, anil.

Asked: May 08, 2017 - 10:47 am UTC

Last updated: July 22, 2019 - 10:17 am UTC

Version: 4.0.1.14

Viewed 10K+ times! This question is

You Asked

Hi Tom,

we are trying to create table/column value(count) constraint by using trigger.
what i am trying is, for table A, column name:'value'. this column should not allow more than two 'YES' values. if it encounter any third 'YES' value it has to roll back the transaction and should not commit. i tried with below code. but the Rollback is not working as excepted. please can you advice.

create or replace TRIGGER "ETL_TEST"
BEFORE INSERT OR UPDATE ON TMP_USER
FOR EACH ROW
DECLARE
Record_Count NUMBER;
In_Value VARCHAR2(8) := 'YES';
PRAGMA AUTONOMOUS_TRANSACTION;
ex_invalid_id EXCEPTION;
BEGIN
EXECUTE IMMEDIATE 'select count(VALUE) from TMP_USER where VALUE = ''' || In_Value || '''' INTO Record_Count;
dbms_output.put_line('RECORD_COUNT : ' || Record_Count) ;
if (Record_Count >= 2)
then
ROLLBACK;
dbms_output.put_line('MESSAGE: THE VALUE CANT INSERT MORE THAN 2 TIMES') ;
end;
ELSE
COMMIT;
end if;
END;

and Connor said...

That wont work.

A long discussion on that here

https://blogs.oracle.com/oraclemagazine/the-trouble-with-triggers

That article also has a solution for you - a materialised view to handle the count.

EDIT: 22 July 2019 - fixing link

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Robert, May 09, 2017 - 11:53 am UTC

That's a great article, though I disagree with Tom's statement that the function-based index is a bad hack. That seems like a simpler and cleaner method than generating views to combine tables and materialized views to enforce rules.
Connor McDonald
May 10, 2017 - 1:19 am UTC

"I disagree with Tom's statement that the function-based index is a bad hack"

I agree with your statement.

I propsoed the mview for the question posed here, because they need to allow 2 rows with a particular value, rather than 1.

Link is broken

Nat Dunn, July 19, 2019 - 2:11 pm UTC

It's not useful because the link is broken. I'm sure it would be useful otherwise. :-)
Chris Saxon
July 22, 2019 - 10:17 am UTC

Thanks, I've updated the link.

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library