Counting Records in a Transaction Trigger

I would like to keep a count of the records that come into our database by date, so want to build an insert trigger on the table (if you don't see date=sysdate in the stats table create a new stats record, otherwise just add one to the counter where date=sysdate).
This is fairly straightforward if I use a BEFORE INSERT ON EACH ROW trigger, however for performance reasons I'd prefer to make this a transaction trigger (probably AFTER INSERT).
Our application brings in records and commits hundreds at a time. Is there a way I can get the number of records commited in the current transaction so I can add that to my counter?
Hope this is clear. Currently I have:
CREATE OR REPLACE
TRIGGER table1_insert
     BEFORE insert ON table1
     REFERENCING NEW AS NEW OLD AS OLD
     FOR EACH ROW
declare     
last_date date;
v_rows_processed integer;
BEGIN
     update stats_table set record_count = record_count + 1 where to_char(stats_date,'yyyymmdd') = to_char(sysdate,'yyyymmdd');
     v_rows_processed := SQL%ROWCOUNT;
if v_rows_processed = 0 then
     insert into stats_table (stats_date,record_count) values(sysdate,1);
end if;
END table1_insert;
Is there any way I can do this as a transaction trigger?
Thanks

Can't you get hold of the total rowcount in e.g. a global package variable (or alternatively in a sys_context variable)?
SQL> CREATE TABLE t (a INTEGER)
Table created.
SQL> CREATE OR REPLACE PACKAGE pkg
AS
   g_cnt   INTEGER := 0;
END pkg;
Package created.
SQL> CREATE OR REPLACE TRIGGER t_1_trg
   AFTER INSERT
   ON t
   FOR EACH ROW
BEGIN
   pkg.g_cnt := pkg.g_cnt + 1;
END t_1_trg;
Trigger created.
SQL> CREATE OR REPLACE TRIGGER t_2_trg
   AFTER INSERT
   ON t
BEGIN
   DBMS_OUTPUT.put_line ('Totol Rows inserted: ' || pkg.g_cnt);
  /* Insert in some stats table ..etc .. */
END t_2_trg;
Trigger created.
SQL> EXEC pkg.g_cnt := 0
PL/SQL procedure successfully completed.
SQL> INSERT INTO t
   SELECT ROWNUM
     FROM all_objects
Totol Rows inserted: 43052

Similar Messages

  • Oracle DB 10g - Count records from a subquery is to slow. (after tuning)

    Hi everybody:
    I have the following problem.
    1.- I have a transactional table with 11 millions of records.
    2.- The user asked for a few reports, to know some sumarized data for business decisions.
    3.- Initialy the query was developed in a development environment, with a subset smaller than the actual data mentioned in label 1.
    4.- When the report was delivered to the end user, the report never return data.
    5.- at this point, we performed tuning, adding indexes, re-writing the query, using hints, etc. and the following scenario is ocurring:
    a) the query without the count, before the tuning was taking about 3 to 5 minutes, and returned aproximatelly 332,000 records-.
    b) the numer of records was counted and this query takes aproximatelly 15 to 23 minutes.
    c) after the tuning, the raw data, returns in 1 second, we used some b-tree indexes, some FBI (because the report needs to filter by to_char functions).
    that time is ok for us, 1 second is a great time in comparison with the 3 to five minutes.
    d) the funny thing, is that when we add a simple count(1), count(x) or wathever flavor of count, the count takes about 3 minutes to return, with the 332,00
    records. is better than de 15 minutes of course, but we dont need count(1), we need to use group by, order by, etc, and will increase the time of query.
    6.- Another thing is happening, if I use count(1) with a transactional table with 600,000 records, without filtering, the count returns in les than 2 seconds. Even if the data is more than the result of my query defined in label 5.c, and that query returns in 1 second.
    Please help me with this, I know that maybe is something that i'm not considering on tuning. Or if there is a way to run this count query faster, please let me know.
    This is the query:
    WITH historial_depurado_v AS (
    select serie, identificador,
           cc_form_cc_tifo_tipo_forma
          ,cc_form_serie
          ,cc_form_folio
          ,estatus_nuevo
          ,to_char(fecha,'MM') Mes
          ,to_char(fecha,'YYYY') Anio  -- the table has a FBI for this.
          ,get_recaudacion_x_forma (hifo.CC_FORM_CC_TIFO_TIPO_FORMA
                                   ,hifo.CC_FORM_SERIE
                                   ,hifo.CC_FORM_FOLIO) Recaudacion  -- function for description.
    from  cc_historial_formas hifo
    where not exists (select 1
                         from ve_tipos_placas tipl
                        where tipl.cc_tifo_tipo_forma = hifo.cc_form_cc_tifo_tipo_forma)
    SELECT serie
      FROM historial_depurado_v hide
    WHERE Anio = '2009'  -- using the function based index.
       AND Mes = '01'
       AND Estatus_nuevo = 'UT'
    -- returns in 1 second, but if I use count(serie) takes 3 to 5 minutes, and still is not complete, I need to use group by some fields returned by the firs subset.
    -- if I count a table with more records, returns in 2 seconds.

    alopez wrote:
    WHERE Anio = '2009'  -- using the function based index.
    AND Mes = '01'
    AND Estatus_nuevo = 'UT'
    Also, i'm not sure if your internal comment is correct, but if you have a function based index on any of those columns, it will ONLY work when you apply the exact function as defined in the FBI (you aren't using any functions on ANY of your columns).
    An example.
    create table use_the_fbi
       column1  date
    insert into use_the_fbi
    select
       trunc(sysdate, 'dd') - level
    from dual connect by level <= 10000;
    create index use_the_fbi_FBI on use_the_fbi (to_char(column1, 'YYYYMM') );
    exec dbms_stats.gather_table_stats( user, 'USE_THE_FBI', cascade=> true, method_opt=> 'for all hidden columns');Let's try without querying in the manner in which we defined the index.
    explain plan for
    select *
    from use_the_fbi
      4  where column1 = '201006';
    Explained.
    Elapsed: 00:00:00.01
    TUBBY_TUBBZ?@xplain
    PLAN_TABLE_OUTPUT
    Plan hash value: 1722805582
    | Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |             |   100 |   900 |     7   (0)| 00:00:01 |
    |*  1 |  TABLE ACCESS FULL| USE_THE_FBI |   100 |   900 |     7   (0)| 00:00:01 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$1 / USE_THE_FBI@SEL$1
    Predicate Information (identified by operation id):
       1 - filter("COLUMN1"='201006')
    Column Projection Information (identified by operation id):
       1 - "COLUMN1"[DATE,7]
    23 rows selected.
    Elapsed: 00:00:00.02Sad Christmas .. no index love.
    Now, query as we defined the index
    explain plan for
    select *
    from use_the_fbi
    where to_char(column1, 'YYYYMM') = '201006';
    Explained.
    Elapsed: 00:00:00.01
    TUBBY_TUBBZ?TUBBY_TUBBZ?@xplain
    PLAN_TABLE_OUTPUT
    Plan hash value: 268331390
    | Id  | Operation                   | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |                 |    30 |   450 |     2   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| USE_THE_FBI     |    30 |   450 |     2   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | USE_THE_FBI_FBI |    30 |       |     1   (0)| 00:00:01 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$1 / USE_THE_FBI@SEL$1
       2 - SEL$1 / USE_THE_FBI@SEL$1
    Predicate Information (identified by operation id):
       2 - access(TO_CHAR(INTERNAL_FUNCTION("COLUMN1"),'YYYYMM')='201006')
    Column Projection Information (identified by operation id):
       1 - "USE_THE_FBI"."COLUMN1"[DATE,7]
       2 - "USE_THE_FBI".ROWID[ROWID,10], TO_CHAR(INTERNAL_FUNCTION("COLUMN1"),'YYYYMM')[VA
           RCHAR2,6]
    27 rows selected.
    Elapsed: 00:00:00.03
    TUBBY_TUBBZ?Happy times.

  • How to count records in a page which are in detail section

    Hi
    Is there a option to count records in detail section and so that based on that can apply a formula.

    Hi
    can i place the below two formulas in section experpt ?
    my report is like
    gh#1 
    details-----which contains transactions related to above group for a country
    group footer#1contains line '--
    if for india there are 3 records in the same page there can be 2 or 3 records in detail section. like that a page can contain more than one country. if number of records are more and coming in next page then the whole section should be moved to new page.
    that is my req. can u suggest accordingly.....
    i want to count the number of records in detais which will vary also how can i put formula when they are going to next page?

  • Process records in a transaction table in real time

    We are currently designing a new system which basically needs to process records from a transaction table. We are envisaging to have approximately 100000 records per hour. There is no need to process each transaction independently as the external process will process all records residing in the table which have not been processed as yet.
    We are basically looking at various options:
    1) have the external process run continuously, select all records in the table, process them and delete them and then start the process again
    2) have the external process run continuously, select all records in the table, process them, update a status flag and then start the process again processing only those records with their status not yet updated
    3) fire a trigger for each record launching the external process (if it is not running yet)
    4) have a separate table containing a timestamp which is updated via trigger for every transaction that is inserted in the transaction table. Have the external process run continuously and only process those records which have exceeded the previous timestamp.
    Would appreciate any ideas you may have how to tune this process and your views regarding the options mentioned above(or others you might have)
    Thanks a lot.

    user9511474 wrote:
    We are currently designing a new system which basically needs to process records from a transaction table. We are envisaging to have approximately 100000 records per hour. There is no need to process each transaction independently as the external process will process all records residing in the table which have not been processed as yet.My busiest table collects up to 50 million rows per hour (peak periods in the day) that also needs to be processed immediately (as a batch) after the hour. I use partitioning. It is a very flexible and there are very few (if any) performance knocks.
    The entire data set has to be processed. With a partition that means a full scan of the table partition - and the ability to do it using parallel query. No additional predicates are needed, except the to have the CBO apply partition pruning. In other words, the predicate enables the CBO to narrow down the SQL to the previous hour's partition only.
    No additional predicates needed like a STATUS flag to differentiate between processed and unprocessed rows - as the entire data set in the partition is unprocessed at that time. (such a flag approach will not be very scalable in any case)
    Also, I do not use external processes. Too expensive performance wise to ship data all the way from the Oracle buffer cache to some external process. And parallel query is also not an option with an external process as the OCI does not provide the external process with a threading interface in order to hook into each of the data output streams provided by the parallel query clients.
    I stay inside PL/SQL to perform the data processing. PL/SQL is even more capable than ProC/C++ and Java and .Net in this regard.
    The execution interface to drive the scheduling of processing is DBMS_JOB. Straight forward and simple to use.
    The basic principles of processing large data volumes in Oracle is to effectively use I/O. Why use indexes when an entire data set needs to be processed? Why perform updates (e.g. updating a status flag) when the data model and physical implementation of that can eliminate it?
    I/O is the most expensive operation. And when dealing with a large volume, you need to make sure that every single I/O is actually required to achieve the end result. There's no room to waste I/O as the performance penalties are hefty.

  • Counting records in Visual Composer

    Hi folks,
    I do have question I cannot find a solution ( maybe due to christmas turkey paralysis )
    I am using VC to call a RFC function in ERP system 'RFC_READ_TABLE' to access data from table.
    The table I access is a customer table containing Delta- Data
    Actually the system RFC function returns all records ( normally between 1 and 10 records).
    On VC side I'd like to display only the number of records to inform if new data is available.
    How can I count records internally in VC?
    ( I do not like to bring in data directly into BI because the application I write will merge BI Query data with non BI data)
    I'D like to use standard RFC function to receive data, but first hand I'd like to decide by number of entries whether to use data or not.
    Any help is appreciated
    TIA

    Hi Prachi,
    that's it.
    I never used that functionality for plain counting records being returned by tables
    It woks perfect.
    The glory shiny points are yours.
    Joerg

  • How to count records from 2 tables and show in RDLC Report

    hi all,
    its being a one day searching for the solution but No Luck.
     I have two SQL tables tblstudetail and tblfeereceiptdetail.
    i just want to count records from both tables and show in RDLC report.
    I tried SQl Query Like This:
    select a.session, a.course,
    Count(CASE a.ADstatus WHEN 'OK' THEN 1 ELSE 0 END ) AS Admission,
    Count(CASE s .I_receiptstatus WHEN 'OK' THEN 1 ELSE 0 END) AS Feeprint
    from
    tblstudetail a
    FULL join
    tblfeereceiptdetail s on s.studentID = a.studentID
    where a.session = '2015' AND s.Fsession = '2015' AND a.adcat = 'Regular'
    GROUP BY a.session,a.course
    ORDER by a.course
    The result Show the Same Value in Both columns
    Session    Course      Admission       FeeDetail
    2015          B.A. I               275              275
    2015          B.A. II              307             307
    2015         B.A. III             255            255
    2015          B.Sc. I             110             110
    2015           B.Sc. II           105            105
    2015          B.Sc. III            64               64
    Actully I want to Count How many ADMISSION have been Taken(FROM tblstudetail) and How many FEE RECEIPT have been Print (From tblfeereceiptdetail).
    please guide me for this as soon as possible.
    thanks in advance...

    I am counting 'OK' in both the table columns I.e 'ADstatus' in tblstudetail and 'feereceiptstatus' in tblfeereceiptdetail
    please suggest me

  • Can the Condition records in the transaction NACE be transported?

    Can we Transport the Condition records in the transaction NACE from one system to another ( I mean from Dev to Quality).
    I have navigated through all the menu in the transaction NACE but haven't found any link for transport.
    Any help pls.

    Hi,
    Please find the bellow thread which is related to NACE transaction.
    <<link removed>>
    Regards,
    Goutam Kolluru.
    Edited by: goutam kolluru on Feb 1, 2012 4:56 AM
    Edited by: kishan P on Feb 1, 2012 11:48 AM

  • BAPI for Purchase Info record creation - ME11 transaction

    Hi,
      Is there any bapi or function modules which will create the Purchase info record in Me11 transaction and also bapi for change Purchase info record in Me12 transaction?
    Points will be awarded.
    Regards,
    vinoth.

    Hi,
    ME_MAINTAIN_INFORECORD
    ME_UPDATE_INFORECORD
    ME_GET_INFORECORD_CONDITIONS
    ME_PRICING_INFORECORD.
    ME_DIRECT_INPUT_INFORECORD
    ME_POST_INFORECORD.

  • BDC Recording for 3 transactions in SD

    i need to cancel contracts using these transaction sequentialy i.e VF46 VF11and VF42 using bdc .how to go about it in recording for 3 transactions
    regards
    shankar

    Hi try this,
    Call one BDC after the another, Like if u want to create a sales order and then correspondingly display it as well, u can capture the sales order created afer ur first BDC theu the messages mostly in SYMSGV1 and using this u can do a call txn skip first screne of VA03.
    If u are talking about session, get 2 session names and move them to different sessions or if both txn are dependant on each other, move it one after the other thru call txn. It is the same, howmany ever trx u wabnt to post thru BDC.
    OR
    After your call transaction stmnt, check for sy-subrc = 0 and refresh bdc internal table.
    Populate the bdc internal table for the new trxn and then call the trxn using call transaction stmnt.

  • BDC Recording for cm07 Transaction

    Hi Everyone,
    I'm doing BDC recording for CM07 transaction. In Recording, i need to give a print command  by specifying the spool title.
    For this, after opening the print window, i need to click the 'properties' button, and then select the spool title and input the value.
    But I'm unable to do the recording of this print dialog box. The recording ends as soon as I give the print command.
    Can anyone please tell me the solution to it.
    Thanks and Regards
    Rishika bawa

    Hi,
    See via transaction SHDB:
    SAPLCORU_S     0100     X
    BDC_OKCODE     BU
                                                           AFRUD-RUECK     0000000000
                                                           AFRUD-AUFNR     100051152
                                                           AFRUD-VORNR     0010
                                                           AFRUD-LMNGA     100,000
                                                           AFRUD-MEINH     PC
                                                           AFRUD-XMNGA     2,000
                                                           AFRUD-ISM01     200
                                                           AFRUD-ILE01     PC
    The table for confirmations is AFRU.
    Best regards,
    Leandro Mengue

  • Counting records in crosstab report

    I am very new to the reporting world so apologies if this seems so simple.
    I am trying to understand how count records that meet certain criteria and I am at a loss as to how to make it work (Crystal Reports 2008)
    I am setting up a cross tab report where I am want to count records that vwSubscription.status="Active" AND vwSubscription.isDues=True
    I think I should be creating a Formula Field that tests the status and dues record and when they both meet the correct criteria then have the Formula Field in the Summarized field of the Cross Tab Expert...
    make sense? please help

    Yes. You should create a formula like this
    IF vwSubscription.status="Active" AND vwSubscription.isDues=True THEN
    1
    And in Cross tab Create A Sum  of this field under Summary fields.
    If you want this value to be displayed based on some group, cross tab will be a good option, else you can create a sum of this field and place it in Report header to get the total.
    HTH,
    Jyothi

  • Mysql database, counting records

    Hi!
    I have to store measured data to MySQL database. During this process I would like to count a number of records in a database table. It is also necessary to filter records. I'm using the SQL statement as follows:
    SELECT COUNT (fieldname) AS cnt FROM table WHERE condition
    Because I haven't got any result I've created a small database "mysweetdb" and table "icecream" to test my VIs (see picture bellow).
    The VI is attached. The result of counting is a 2D array (DB Tools Fetch Recordset Data.VI output) with one element (one row and one column). This element contains no data.
    I usually don't give up easily so I've created a similar MS ACCESS database and counted data in it. I've got a correct answer: 3. So it might be possible that there is something wrong with MySQL driver. But I've created a small Delphi project and I've counted records in MySQL database and MS ACCESS database. Both results were correct.
    Can anyone explain where is the problem in communication between LabView and MySQL database?
    Versions: XAMPP for Windows 1.7.3, LabView Developer Suite 2010 SP1, MySQL 5.1 ODBC driver
    Thanks in advance for your suggestions.
    Attachments:
    Count records.vi ‏19 KB

    ContDivConsult,
    thank you for your answer. An updated version of my VI is attached. It uses two options: LabSQL library and DB Connectivity Toolkit. LabSQL gives correct results.
    Regards,
    Ljubo.
    Attachments:
    Count records.vi ‏25 KB

  • Error: The sort order specified for distinct count records is incorrect

    When processing a measure group with a distinct count measure in it, i get the following error:
    "The sort order specified for distinct count records is incorrect."
    I have no idea what this means - any ideas?

    I had the same problem and your fix worked.  In more detail, the problematic field was contract_no.  I added a named calculation to the table in the Data Source View with the formula CHECKSUM(contract_no).  Then I created the distinct count measure on that named calculation.  And, lo and behold, the errors disappeared! 
    Thank you to Frank.
     - CindyCindy P Hoskey

  • COUNTING RECORDS AND DETERMINING AVERAGES IN REPORT WRITER

    I HAVE 10 GROUPS. I WANT TO BE ABLE TO COUNT RECORDS AND DETERMINE THE AVERAGE DAYS FOR EACH GROUP. I GET DAYS BY SUBTRACTING THE RECEIVED DATE FROM THE RESULT DATE. I WANT TO DETERMINE THE AVERAGE DAYS AND THE NUMBER OF RECORDS IN THE TOP 10%, THE TOP 20%, THE TOP 30%, THE TOP 40%, THE TOP 50%, THE TOP 60%, THE TOP 70%, THE TOP 80%, THE TOP 90%, AND THE TOP 100%. HOW DO I CODE MY LOOP IN PLSQL TO DO THIS? CAN I DO THIS IN REPORT WRITER?

    I am not sure about the exact thing that you are requiring. but you can get the top 100 and top 20 or top 300 etc. by using the ROWNUM function in sql statement.
    thanks

  • Leaf Count Record

    After backing up my hard drive and booting from my freshly made eDrive, I ran TechTool Pro 6's "Volume Rebuild" and after that ran it showed me the results, as usual. There were a few green items but one red. The "Leaf Count Record" went from 1777 to 625. I tried to find out what a Leaf Count Record is by googling it but only count find things on the error associated with this.
    So my first question is: What is a Leaf Count Record?
    Secondly, is there any problem with my Leaf Count going down, and should i be worried about it?
    Note: i went ahead with the rebuild since all the information i could find on Leaf Count Record is mostly about the Leaf Count going up and not down.

    After backing up my hard drive and booting from my freshly made eDrive, I ran TechTool Pro 6's "Volume Rebuild" and after that ran it showed me the results, as usual. There were a few green items but one red. The "Leaf Count Record" went from 1777 to 625. I tried to find out what a Leaf Count Record is by googling it but only count find things on the error associated with this.
    So my first question is: What is a Leaf Count Record?
    Secondly, is there any problem with my Leaf Count going down, and should i be worried about it?
    Note: i went ahead with the rebuild since all the information i could find on Leaf Count Record is mostly about the Leaf Count going up and not down.

Maybe you are looking for

  • My ical will not open

    I instailled .mac but it was 04 editon and ever secne then it will not open and the image has change to two peices of paper with a pen and a ruler and a burah i have tired to reinstaill it but it says try insatilling it again plaese help

  • Can I have Two iPods on one iTunes???Help Me!

    Hey There, I'm just wondering if I can have 2 ipods on the same iTunes (can i put my library on a friends new ipod?????) Help me! Last time i tried something with i tunes i lost my music. Thx

  • Browser flash detection script

    I need to put a flash detection scrip on my page as some of my friends can't view my page. Can you advise? Thank You Kevin

  • Hit "Save as Adobe pdf" and pic came out on top of text box.

    Win 7.0 64 bit, acrobat 11.0.10 word 2010, created a .docx file woth a pic and a tex box on top of pic.- hit Save as Adobe pdf and pic came out on top of text box.

  • Encore cs4 files for creating dvd? where are the stored?

    Hi, I am in trouble. I have been working on project in Adobe Prem cs4 dragged it into encore.. all ok. made dvd.(some links I did didn't work...my learning) made dvd missed 3 seconds of footage. sorted in A prem. all gd in encore. remade dvd ( 4 hour