Select previous max(date) and current max(date) in trigger

Good mroning fellows!
I am trying to develop a row level trigger that inserts data into another table after insert.
Within the trigger I need to calculate a couple of averages based on dates. Therefore I need to select the date of the previously entered record and calculate the days between this last record and the current entry that was just saved.
Is it possible to write it like that in the trigger?
create or replace
TRIGGER borki.set_tageswerte
  AFTER INSERT
  ON borki.fangzahlen
  FOR EACH ROW
-- WHEN (NEW.qb_nr > 0 AND NEW.lrt_fl_id > 0) 
DECLARE
old_date        date;
latest_date     date;
days            number;
avergae_amount  integer;
BEGIN
old_date := (SELECT max(:old.date_datum)
     FROM borki.fangzahlen
     WHERE lng_falle = :new.lng_falle
     AND int_fallennummer = :new.int_fallennummer
     AND lng_schaedling = :new.lng_schaedling);
latest_date :=  (SELECT max(:new.date_datum)
     FROM borki.fangzahlen
     WHERE lng_falle = :new.lng_falle
     AND int_fallennummer = :new.int_fallennummer
     AND lng_schaedling = :new.lng_schaedling);
days := latest_date - old_date;
average_amount := (SELECT CASE
                   WHEN f.int_volumen > 0 AND f.lng_schaedling = 1 THEN f.int_volumen * 40
                   WHEN f.int_volumen > 0 AND f.lng_schaedling = 2 THEN f.int_volumen * 550
                   WHEN f.int_anzahl > 0 THEN f.int_anzahl
                   END
             / days AS tagesfang
        FROM borki.fangzahlen f
        WHERE f.lng_falle = :new.lng_falle
         AND f.int_fallennummer = :new.int_fallennummer
         AND f.lng_schaedling = :new.lng_schaedling
         AND days > 0
         AND ((f.int_anzahl > 0) OR (f.int_volumen > 0)))
     INSERT
         INTO fangzahlen_tageswerte
          lng_falle, date_datum, int_fallennummer, lng_schaedling, int_volumen, int_anzahl, lng_fangzahlen
        VALUES
        (SELECT f.lng_falle,
                   :new.date_datum, :new.int_fallennummer,
                   :new.lng_schaedling, :new.int_volumen,
                   :new.int_anzahl - ((y-1)*rec.tagesfang),
                   :new.objectid
END;thanks for sharing your wisdom mith me! :-)
Sebastian
Edited by: skahlert on 07.04.2010 07:04

Hello Tubby!
You're correct!
I'll take the time and show you what I got and what I need!
I am working with an Apex frontend where users enter scientific data for beetle monitoring.
The data entered consists of --> date_datum: date when last trap was emptied
--> int_volumen: the volume of the trap (used to calculate found specimen when int_anzahl is null)
--> int_anzahl: amount of found beetles
--> lng_schaedling: type of beetle (1 or 2)
--> lng_falle:trap number
--> int_fallennummer: sub-trap type (1 or 2)
Background info: Data is entered once or twice a week for each trap. After the data has been entered I need to calculate the mean average depending on the volume or amount.
Therefore I need to sum the colume or amount and divide it by the period of days since the current and last trap removal (that's when the bugs are counted and data is manually entered to the DB). For each day between the last and current trap removal I need to add one record in table fangzahlen_tageswerte (in my proc still called "test" for obvious reasons) that contains the mean average value of found beetles.
I hope I could point out my demand without confusing you!
PS: my problem --> very little background info concerning the entomological monitoring of this beetle type ;-), limited pl/sql skills and the problem that I need to run this procedure for each new record only. If you could show me how to make sure that data is not stored in table fangzahlen_tageswerte multiple times, I could called it directly in APEX.
Otherwise I'd suggest to create a trigger that launches this procedure below and parses the :new.parameters into my pocedure.
Another problem: this might work for insert statements. However, obviously I have to correct the mean values if raw data in table fangzahlen has been updated. Should I call another procedure after update on tbl fangzahlen or integrate that part into the procedure below? Doesn't matter I guess, right?
create or replace
PROCEDURE             "PR_FANGZAHLEN_TW_SK" (
   pr_falle          NUMBER,
   pr_fallennummer   NUMBER,
   pr_schaedling     NUMBER
IS
   old_date                  DATE;
   diff_days                 NUMBER (10);
   tagesfang                 NUMBER (12);
   y                         NUMBER (10);
BEGIN
   /*Query date of previous record and store it into variable old_date*/
    select date_datum into old_date from
    (select f.date_datum, row_number() over (order by f.date_datum desc) rn
    from borki.fangzahlen f where f.lng_falle = pr_falle
    and f.int_fallennummer = pr_fallennummer
    and f.lng_schaedling = pr_schaedling) where rn=2;
    select max(f.date_datum) - old_date into diff_days from borki.fangzahlen f
     where (f.lng_falle = pr_falle)
     and (f.int_fallennummer = pr_fallennummer)
     and (f.lng_schaedling = pr_schaedling);
   FOR rec IN (select sum((case
                   when f.int_volumen > 0 and f.lng_schaedling = 1
                      then f.int_volumen * 40
                   when f.int_volumen > 0 and f.lng_schaedling = 2
                      then f.int_volumen * 550
                   when f.int_anzahl > 0
                      then f.int_anzahl
                end
             / (f.date_datum - to_date(old_date))) as tagesfang
        from borki.fangzahlen f
        where (f.lng_falle = pr_falle)
         and (f.int_fallennummer = pr_fallennummer)
         and (f.lng_schaedling = pr_schaedling)
         and ((f.date_datum - to_date(old_date)) > 0)
         and ((f.int_anzahl > 0) or (f.int_volumen > 0))) 
      LOOP
            y := 1;
      WHILE y < diff_days + 1
      LOOP
      /* Insert FANGZAHLEN_TAGESWERTE*/
       IF  y < diff_days
       THEN
         INSERT INTO test
                     (lng_falle, date_datum, int_fallennummer,
                      lng_schaedling, int_volumen, int_anzahl,
                      lng_fangzahlen)
            SELECT f.lng_falle,
                   old_date + y, f.int_fallennummer,
                   f.lng_schaedling, f.int_volumen, rec.tagesfang,
                   f.objectid
              FROM fangzahlen f
             WHERE     f.lng_falle = pr_falle
                   AND f.int_fallennummer = pr_fallennummer
                   AND f.lng_schaedling = pr_schaedling
                   AND (f.date_datum - old_date) > 0
                   AND ( (f.int_anzahl > 0)
                OR (f.int_volumen > 0) );
       END IF;
         y := y + 1;
      END LOOP;
END LOOP; -- end of cursor
EXCEPTION
   WHEN NO_DATA_FOUND
   THEN
      NULL;
   WHEN OTHERS
   THEN
      -- Consider logging the error and then re-raise
      RAISE;
END "PR_FANGZAHLEN_TW_SK";regards,
Seb

Similar Messages

  • Keyboard shortcuts: current day and date, and current time?

    I would like to know keyboard shortcuts for entering current day and date, and current time (separated entries) in Numbers. Something that Excel does easily. Thank you, Ian

    Ian,
    Numbers does not have predefined key command for Insert Date & Time as you can see from this screenshot:
    All menus show the key commands on the very right (if there is a ke command).  You can add you own, custom, key commands by opening system preferences and selecting the Keyboard panel, then the "Keyboard Shortcuts" segment:
    Click the "+" then a modal dialog will appear.   Select the application from the pop, then enter the exact name if the menu item, and, finally, your desired key combination:
    You can do this for any application

  • Date and Time Stamp - Data Code

    I am trying to import HD video from a Sony video camera to iMovie, but require date and time stamp data code to display on the video.  The computer imports the video in HD without problem, but does not display the data code information.  Options allow for adjusting the date and time within the video clips, which proves the code is in there somewhere, but there are no options to display the date and time stamps. 
    I have previously accomplished this by running the camera in real time through a Pinnacle movie box, but this is time consuming, and hinders video quality, rendering in standard definition. 
    Can anyone please assist? 
    Thanks

    Date stamp data is not something read by FCP ... try iMovie,
    Alternatively, check the camera's output options, it may be possible to output the data burnt-in on the s-video or some such ... if you have the requisite i/o hardware you could then digitize from that signal path

  • Actions- Incorrect Entry Date and Corrected Entry Date

    i am going by the link below
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/48/35c5a94abf11d18a0f0000e816ae6e/frameset.htm
    But I am not able to find "Incorrect Entry Date" and "Corrected Entry Date" Actions anywhere. Not even the drop down of Actions List
    Where are they acually?

    As said by our Gurus PA41 is used to change the Corrected entry and incorect entry
    u can do the same thru PA40 if u select 70 and 71 action types this screens are nothing bu the screens u see in PA41
    for ur info

  • Material Master Data and PO Master Data Table

    Dear SAP Gurus and Expert,
    Currently user is having a new integration system which link to SAP, and they require the migration of Material MAster Data and PO master data.
    As a result of that, what table can be accessed in SE16 in order to get all the material master data and PO master data to be exported to excel fil format.
    Thank you
    Regards

    Hi,
    For material master data
    MARA                           General Material Data
    MARC                           Plant Data for Material
    MAKT                           Material Descriptions
    MARD                           Storage Location Data for Material
    You can enter MA* in SE16 and press F4 too get all the tables according to the views.
    For Purchase order
    EKKO
    EKPO
    EKBE
    EKKN
    Search for EK* in SE16.

  • How can we delete SID table data and Text table data

    Hi,
    How can we delete SID table data and Text table data of any
    InfoObject.

    Hi,
    Go to transaction SE14, give the technical name if the table:
    /BIC/T<InfoObject Name>   for Text Table
    /BIC/S<InfoObject Name>  for SID Table
    Select "Table" in the given 4 options below  &  hit Edit button.
    in the next screen select "Direct"
    & also select "detele data" radio button.
    & hit  "Activate & adjust database".
    this will delete the complete data from the tables.
    Note: before deleting the SID's make sure of the consequences & after effects.
    Also the SID gets generated the next time you load master data/transaction data only for those records which were loaded..
    Regards,
    Iliyas

  • Month to Date and Year to Date Scenarios

    <b>Dear SAP BI Gurus,
    Can anyone please give me guidance how to create a Month to Date and Year To Date Scenarios (Variables perhaps?) for 0SRR_CF_C1?  The date is in decimal and not DATE format…  I’m assuming the reason for this is to get the Time variance….  Nonetheless, I’d like to create a MTD and YTD scenario for reporting.
    Much Thanks
    Philips Manalaysay</b>

    Hi,
    You should take a look at the blog and doc below.
    /people/vikash.agrawal/blog/2006/10/17/enable-trend-reporting-150-by-manipulating-variable-value
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/25d98cf6-0d01-0010-0e9b-edcd4597335a
    Regards,

  • I just got a new iPhone and i set up iCloud on my girlfriend's account. To change it on settings it says delete account. Will this delete her all her data and back up data for iCloud on her iPhone and iPad?

    I just got a new iPhone and i set up iCloud on my girlfriend's account. To change it on settings it says delete account. Will this delete her all her data and back up data for iCloud on her iPhone and iPad? Can i change it without deleting it? Please help.

    Delete the account on your phone. This will not delete any data on her phone or iPad, or data stored in iCloud.

  • PO creation Date and Invoice creation Date

    Hi,
    Can any one help me regarding which table I can look for PO creation date and Invoice creation date. I require these fields for my reporting requirement.
    Thanks in advance,
    Arvind.

    Thanks for your response Bala.
    I got the Table which I require. I have one more question on this.
    Can you tell me Invoice Creation Date is RBKP-BLDAT(Document Date in Document) or RBKP-BUDAT(Posting Date in the Document) and PO creation Date is EKKO-AEDAT(Date on which the record was created) or EKKO-BEDAT(Document Date in Document).
    Points already rewarded.

  • Planned order creation with PDS valid on only order start date and not finish date

    Hi All,
    We have requirement to allow creation of planned order manually if production version is valid on order start date and not finish date.  This is because lead time of order is longer. I refered OSS notes 385602. I could find out solution for this is implementation of OSS note 694140 to change validity mode at activity level to consider start date of first produce activity  in validity interval. Problem is even If I create order in APO by implementiong this note planned order is not transfered to ECC and it gets stuck with error production version not valid.
    Is there any way in ECC to control this? Any config or customization?
    Regards,
    Santosh

    Nilesh,
    I think there is a simple procedural skip happening in your business process. You are right when a planned order is created after MRP it would default assign it to the first available production version. 2options available for us,
    1. First use transaction MF50 and do the line loading and assign the quantites to the production versions/Production lines, so that the actual capacity planning is getting completed. This way you can have planned orders with both the production versions and matching to your actual line capacity.
    2. Use Quota arrangement concept, to automatically split the Planned orders during MRP for a percentage based on individual production versions.
    Now when backflush is performed S225 table is updated and Planned order qty also gets reduced.
    Hope this helps....
    Regards,
    Prasobh

  • Goods issue date and goods receipt date

    Hi Guys,
                 i was asked to display STO list.They asked me add goods issue date and goods Report date in the o/p columns.So any body can tell me what are the fields for goods issue and goods Receipt date's.?can u guys tell me the Tr code for these fields .?
    Thanks,
    Gopi.

    Hi there,
    I already solve it by myself.
    Actually is i call the initialization twice:
    Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenEntry)
    Thats what make this problem happened.
    Sorry.
    Best Regards,
    danny

  • Process Order Basic Finish Date and Scheduled Finish Date

    Folks,
    I have a requirement from the business to be able to update the Process Order Basic Finish Date and Scheduled Finish Date independently from each other.
    In other words, update the Basic Finish Date and the Scheduled Finish Date cannot change or update the Scheduled Finish Date and the Basic Finish Date cannot change.
    I believe the reason for this is to be able to use the Basic Date to maintain the ATP accurately and keep the Scheduled Date to mark when the order was originally due from the shop floor to be able to measure if orders are being completed on time or late.
    I have worked in tnx OPUZ and had some success with other issues with these dates but I can't seem to make them work independently from each other.
    Or does anyone have any ideas how to measure proces order performance to the production schedule?
    Thank you for your help,
    Greg

    Rajesha, thank you for your reply but it doesn't solve my problem.
    Let me restate my scenario:
    I start a process order and both the basic and scheduled finish dates are the same, June 1.
    At some point, shop floor tells me they will be late and cannot deliver until June 15.
    I need to update a date in the system so the ATP and the MRP planning runs have correct information for promising customers, I will update the Basic Finish date with June 15.
    I also need to keep the original June 1 date in order to measure the shop floor performance to the production schedule to measure how early or late the  order was delivered. How can I keep the original finish date or how can I measure if a process order is early or late??
    Thank you for your help,
    Greg

  • Difference between "Database Variant To Data" and "Variant To Data"

    Can anyone tell me the differnce between the 2 VI's "Database Variant To Data" and "Variant To Data"?
    I am using the database connectivity toolset and making a query.
    I have tried using both, but the give me the same result.
    Attachments:
    Variant to Data.JPG ‏45 KB

    You won't see a difference between these two functions with just a string or other simple data types.  Where you'll see a difference is with clusters and more complex data types that come from the database.  The variants returned by databases can be slightly different than the standard variant.  That is where the Database Variant To Data is needed.  Otherwise, if you are just reading string information, either function will work fine.
    Crystal

  • Using attribute as a set of data and parsing this data

    Hi everyone,
    I present below a (little) challenge with the use of attributes in XQuery. Consider the following XML document:
    <showroom>
    <car id="1">
    <name>Clio</name>
    <family>Renault</family>
    </car>
    <car id="n">
    <name>Q5</name>
    <family>Audi</family>
    </car>
    </showroom>
    Each client of the showroom is identified by a unique Id (e.g., 1,2,3,....). Then, i want to add some data to my XML document which should represent, for each car, the set of all clients' Id that have rented this car.
    The desired XML document could look like this:
    <showroom>
    <car id="1">
    <name>Clio</name>
    <family>Renault</family>
    +*<history>*+
    +*<client id="2"/>*+
    +*<client id="23"/>*+
    +*</history>*+
    </car>
    <car id="n">
    <name>Q5</name>
    <family>Audi</family>
    +*<history>*+
    +*<client id="56"/>*+
    +*</history>*+
    </car>
    </showroom>
    However, by using elements in order to represent the rental historic, the document's size will increase significantly.
    As i use only the clients' id, are there any way to represent the history data using only attributes ?+.
    In the following document, the clients' id are represented, as a set, through the attribute +@history+:
    <showroom>
    <car id="1" history="2,23">
    <name>Clio</name>
    <family>Renault</family>
    </car>
    <car id="n" history="56">
    <name>Q5</name>
    <family>Audi</family>
    </car>
    </showroom>
    However, are there any way to check if a given car of id='x' has been rented by a client of Id='y' ?+.
    Does someone know how to represent the history data (sequence of clients' id), using only attributes, and how to look for a given client's id as explained above ?
    Please suggest. I appreciate your help.

    The two following documents represent examples of the showroom data and the clients' data respectively:
    First document:
    <showroom>
    <car id="1">
    <name>Clio</name>
    <family>Renault</family>
    </car>
    <car id="n">
    <name>Q5</name>
    <family>Audi</family>
    </car>
    </showroom>
    Second document:
    <clients>
    <client id="2">
    <name>...</name>
    <firstname>...</firstname>
    <driverLicence serialNumber="2156311"/>
    </client>
    </clients>
    The DTDs of these documents are defined as follows:
    The showroom DTD:
    <!ELEMENT showroom (car)*>
    <!ELEMENT car (name,family)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT N3 (#PCDATA)>
    <!ATTLIST car id ID #REQUIRED>
    The clients DTD:
    <!ELEMENT clients (client)*>
    <!ELEMENT client (name,firstname,driverLicence)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT firstname (#PCDATA)>
    <!ELEMENT driverLicence EMPTY>
    <!ATTLIST client id ID #REQUIRED>
    <!ATTLIST driverLicence serialNumber ID #REQUIRED>
    Whenever a car is rented, I must add some information either in the same showroom document (it will be better for me) or in another document which relies rented car id with the id of the client which rented this car.
    Thanks in advance for your help.

  • How to stop scheduled ship date and scheduled arrival date from defaulting to sysdate

    Hello,
    We have a business scenario where we are deriving scheduled ship date and scheduled arrival date outside and then imported in the instance with the order. However we find that the scheduled ship date and scheduled arrival date are defaulting to sysdate. The atp flag is set to N for these items. I have checked the defaulting rules, there is no such defaulting rule set for scheduled ship date or arrival date ( screenshot attached) Please share your thoughts on how can I stop scheduled ship date and arrival date date from defaulting to sysdate ?
    Thanks
    Rajesh

    Hi
    Please visit following link. It may be useful.
    How to prevent auto default of schedule ship date in sales order form
    HTH
    sd

Maybe you are looking for

  • EBS 12.1.3 Upgrade issue

    Hi, I installed 12.1.1 with the Vision Database on my machines which has a 64 bit Linux 5 update 5 operating system and everything went fine. After that I decided to upgrade to 12.1.3. I installed the following patches in order they are given below :

  • Attachment in Column - giving runtime exception and "FNDDOCUMENTSEO"."error

    I have created a Attachment VO for a VO from the Fusion App: Advanced Supply Chain Management ( 724). Using the new gallery wizard for "Attachment View Link" I have succesfully finished all 6 steps, created trough this wizard a Attachments Entity ( n

  • Set default result to single page, 999 rows per page

    hi! im using 10g with windows server 2003. everytime i start isqlplus, the default setting is to display the result of a select query to multiple pages with 24 rows per page. i like to have my result in a single page. i can change it in the preferenc

  • OPC server setting

    Hi I`have developed an application client which has shared variables bounded with an OPC server of NI. Sever and Client are on the same machine. My executable works very well. Now if I want install my executable on a machine that has not the OPC serv

  • [Solved][Boost] Condition_variable exception on thread termination

    Hi folks, I'm trying to implement an object that accepts some data and processes it in a separate thread (basically producer-consumer model). The object's thread should run until object destructor is called. To notify of new data I use condition_vari