简体   繁体   中英

how to add trigger to count number of rows automatically after inserting in oracle sql developer

I want to add trigger to count number of movies after inserting!

This is the table to store the count value:

CREATE TABLE mov_count
  (mcount NUMBER);

and the movie table:

create table movie
  (mov_id number primary key,
   mov_title varchar(20),
   mov_lang varchar(20));

This is the trigger I have created:

create trigger count_movie_trg
after insert on movie
for each row
BEGIN

  UPDATE mov_count
  SET    mcount = (SELECT COUNT(*) FROM movie);

END; 
/

After creating this i tried to add movie but its showing mutating trigger/function may not see it error.

Why not just maintain the value without referring to the original table?

create trigger count_movie_trg after insert on movie for each row
begin
    update mov_count set mcount = mcount + 1;
end;

To keep the count up-to-date, you'll need a delete trigger as well.

It is the FOR EACH ROW that bothers you. It is a table-level trigger, so:

Enter a dummy value for beginning (as you'll update it later):

SQL> insert into mov_count values (0);

1 row created.

Trigger:

SQL> create or replace trigger count_movie_trg
  2    after insert on movie
  3  begin
  4    update mov_count c set
  5      c.mcount = (select count(*) from movie m);
  6  end;
  7  /

Trigger created.

Testing:

SQL> insert into movie
  2    select 1, 'Titanic' from dual union all
  3    select 2, 'Superman' from dual;

2 rows created.

SQL> select count(*) from mov_count;

  COUNT(*)
----------
         1

SQL>

Don't use the table at all; use a view instead.

CREATE VIEW mov_count ( mcount ) AS
  SELECT COUNT(*) FROM movie;

db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM