Updating parent row in a self-join table with triggers

Hi Gurus!
Need of a business to update parent row(s) in the same table with triggers (insert, update and delete). Table is having recursive relation and error is coming as mutating error. I was able to do this with MS-SQL server.
Appreciate any help or work around possibilities.
Regards,
SH

SH,
popular solutions to this issue include
- autonomous transactions
- recording (typically in PL/SQL package variables) the rows being processed from the row level triggers and using this information in the after statement level trigger to perform the update on the parent rows
- use a View with an instead of trigger to re-route the DML on your table
Which one to use depends on what exactly you are trying to achieve and how the data hangs together.
Lucas

Similar Messages

  • Join table with additional data

    Hi,
    I'm new to JPA (Toplink Essentials) and I'd like to know how to handle this situation:
    I have ORDER table, ITEMS table and "join table" ORDER_ITEMS which holds refernces to ordered items with quantity of each oredered item.
    Many thanks

    I did mapping as shown in listing. It works for reading, but for writing JPA returns error. Can somebody help?
    Thanks
    [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Column name 'idexpedice' appears more than once in the result column list.
    Error Code: 264
    Call: INSERT INTO vklad_expedice (IDEXPEDICE, IDVKLAD, VAHA, idexpedice, idvklad) VALUES (?, ?, ?, ?, ?)
    bind => [null, null, 0, 4411, 2]
    @Entity
    public class Expedice implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer idexpedice;
    @Temporal(TemporalType.DATE)
    private Date datum;
    @OneToMany(fetch = FetchType.EAGER, mappedBy="expedice", cascade = CascadeType.ALL)
    private List<ExpediceVklad> vklady;
    @Entity
    public class Vklad implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer idvklad;
    private String nazev;
    @Entity
    @Table(name = "vklad_expedice")
    @IdClass(ExpediceVkladId.class)
    public class ExpediceVklad implements Serializable {
    @Id
    private Integer idexpedice;
    @Id
    private Integer idvklad;
    private Integer vaha;
    @ManyToOne
    @JoinColumn(name = "idexpedice")
    private Expedice expedice;
    @ManyToOne
    @JoinColumn(name = "idvklad")
    private Vklad vklad;
    public class ExpediceVkladId {
    @Id
    private Integer idexpedice;
    @Id
    private Integer idvklad;
    SQL tables
    EXPEDICE
    idexpedice
    datum
    VKLAD
    idvklad
    nazev
    VKLAD_EXPEDICE (this is the join table with additional column)
    idexpedice
    idvklad
    vaha
    Edited by: user10933983 on 31.3.2009 13:47

  • How to achieve parent-child relationship using self join?

    my table structure is as follows
    parent child name
    -1     1     A1
    1     2     A2
    1     3     A3
    how to achieve the hierarchy model using self join. this can be easily achieved using "connect by prior". but how to achieve the same using self join?

    Hi,
    Yes, that's definitely possible. If you only need to display two levels from the hierarchy, a self-join is a good option. Make it an outer join if you need to show everyone on one level, regardless of whether they have a match on the other level or not; for example, if you want the output:
    child_name     child_id     parent_name     parent_id
    A1          1
    A2          2          A1          1
    A3          3          A1          1It's good that you posted some sample data. Now post the results you want from that data, and your query (what you think is the best attempt you've made so far). If you haven't tried anything so far, then look at some other simple self-join to get ideas.

  • VPD problem: select for update on join tables with policy on ref table

    In our application we use VPD. Now we ran into an issue. I will try to explain with EMP and DEPT table.
    EMP table has no VPD attached.
    DEPT table has VPD policy that forbids all updates, but allows select. (Policy returns '1=2' for statement type update.
    This query returns no rows:
    select * from emp join dept using (department_id) for update. This makes sense, because I'm going to update both the tables.
    However:
    select * from emp join dept using (department_id) for update of employee_id also returns no rows. THIS IS WRONG. I'm not going to update dept table.
    Any experience with this. Is this a known limitation ?

    I can see all the rows, because there is no select policy.
    However the point is, that VPD should allow me to update the emp table, because there is no update policy.
    With the 'for update of employee_id' clause, VPD should recognize that I'm not going to update the dept table, but only the emp table. But VPD does not recognize this, but applies the update policy of dept to the statement, making the statement to update no rows.
    (Reason behind my question is ADF Business Components, where you have ViewObjects with Referenced Entities. ADF BC generates this type of statement and now we run into this VDP limitation)

  • Query 4 joined tables with internal joins to represent a complex hierarchy!

    I've got to refine/replace a query (Oracle 9i) that
    currently joins rows from four tables in a hierarchical
    fashion that I use to produce a listing like this:
    agency abc 1
    ....division def 1.1
    ........service ghi 1.1.1
    ........service jkl 1.1.2
    ............faq mno 1.1.2.1
    ............faq pqr 1.1.2.2
    ........service stu 1.1.3
    ....division vwx 1.2
    ........service yyy 1.2.1
    ............faq zzz 1.2.1.1
    The change involves allowing for unlimited levels of
    nested child divisions to produce a listing like this:
    agency abc 1
    ....division def 1.1
    ........service ghi 1.1.1
    ........service jkl 1.1.2
    ............faq mno 1.1.2.1
    ............faq pqr 1.1.2.2
    ........service stu 1.1.3
    ....division vwx 1.2
    ........division xxx 1.2.1
    ............division aaa 1.2.1.1
    ............division bbb 1.2.1.2
    ................service aaa 1.2.1.2.1
    ....................faq fff 1.2.1.2.1.1
    ....................faq ggg 1.2.1.2.1.2
    ........service yyy 1.2.1
    ............faq zzz 1.2.1.1
    Notice the insertion of three nested divisions under
    division 1.2 with services and faqs under those. The
    order of names throughout is alphabetic within a nesting
    level.
    Here's the SQL I currently use, without nested divisions
    (it contains extra info that I use to control what and
    how names are displayed):
    SELECT
    agency.agency_id AGENCY_ID,
    agency.agency_type_id AGENCY_TYPE_ID,
    agency.name AGENCY_NAME,
    agency.acronym AGENCY_ACRONYM,
    agency.expiration_date AGENCY_EXP,
    agency.post_count AGENCY_POST,
    agency.stat AGENCY_STAT,
    agency_type.agency_type AGENCY_TYPE,
    division.division_id DIV_ID,
    division.name DIV_NAME,
    division.transfer_number DIV_TRANS_NUM,
    division.expiration_date DIV_EXP,
    division.post_count DIV_POST,
    division.stat DIV_STAT,
    service.service_id SVC_ID,
    service.name SVC_NAME,
    service.taxonomy SVC_TAX,
    service.keywords SVC_KEYWORDS,
    service.action_type SVC_ACTION_TYPE,
    service.sr_form_name SVC_SR_FORM,
    service.expiration_date SVC_EXP,
    service.post_count SVC_POST,
    service.stat SVC_STAT,
    faq.faq_id FAQ_ID,
    faq.name FAQ_NAME,
    faq.expiration_date FAQ_EXP,
    faq.post_count FAQ_POST,
    faq.stat FAQ_STAT
    FROM
    agency,
    agency_type,
    division left join service on
    division.division_id=service.division_id left join
    faq on service.service_id=faq.service_id
    WHERE (
    (agency_type.agency_type_id = agency.agency_type_id)
    AND (agency.agency_id = division.agency_id)
    AND (agency.agency_id = :agency_id )
    It's very fast -- I can retrieve and display 5,000 rows
    in seconds using Perl DBI and CGI -- and very easy to use
    to produce the hierarchical listing of items from the
    four tables. It is also very straightforward since I was
    able to generate the SQL using the SQL modeler in TOAD
    (I'm not the strongest SQL developer so I resort to
    tools).
    I need to get jump-started in the right direction to
    determine what I need to add to my division table
    (div_parent_id?), if I need a div_parent_child table to
    define the relationships (rows with parent_id & child_id
    pairs), and how to change or rewrite the SQL query. The
    CGI form that will be used to define the relationships
    will ask users to define children of a given division. I
    envision presenting a list of divisions with null
    parent_division_id columns for users to select from then
    updating selected rows for selected divsions.
    Thanks in advance for any help/guidance!
    -Gene

    INLINE VIEWS!
    select whatever_you_want
    from (
    SELECT FOLDER_ID, PARENT_FOLDER_ID, FOLDER_NAME
    FROM FOLDERS
    START WITH PARENT_FOLDER_ID = 0 CONNECT BY PARENT_FOLDER_ID = PRIOR FOLDER_ID
    ) tree, FILES
    where tree.folder_id = files.folder_id -- or something like that
    always try to keep the CONNECT BY limited to ONE AND ONLY table. then use that query in a subquery, a WITH clause, an inline view or something. do not try to JOIN or UNION with a CONNECT BY. it won't work the way you think it will, and even it returns the expected results, it will perform terribly.
    * your mileage may vary
    Message was edited by:
    shoblock
    added exclamation marks to show my excitement!!!!

  • Join Table with Collection Array Type

    Hi All,
    I'm trying to join 2 types of tables (real table and array collection type)
    When I wrote this code:
    Declare
    -- Types
    Type cArr Is Record (col1 Number);
    Type tArr Is Table Of cArr Index By Binary_Integer;
    -- Objects
    ocArr cArr;
    otArr tArr;
    Begin
    -- Set Array Table
    ocArr.col1 := 1;
    otArr(1) := ocArr;
    ocArr.col1 := 3;
    otArr(2) := ocArr;
    -- Fetch Records
    For Rec in (Select col1 From Table(otArr) Arr)
    Loop
    Dbms_Output.Put_Line(Rec.col1);
    End Loop;
    End;
    I Get This Error:
    ORA-06550: line 10, column 64:
    PLS-00382: expression is of wrong type
    ORA-06550: line 10, column 58:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 10, column 21:
    PL/SQL: SQL Statement ignored
    I know that I can Use this as sn answer:
    For Rec In 1..2
    Loop
    Dbms_Output.Put_Line(otArr(Rec).Col1);
    End Loop;
    But I need later on to use this collection join with another real table based on values compare like:
    For Rec in (Select a.Col2 From a,(Select col1 From Table(otArr)) Arr Where a.Col1 = Arr.Col1)
    Loop
    Dbms_Output.Put_Line(Rec.col1);
    End Loop;
    Can someone tell me where I'm wrong and how to fix it?
    Thanks,

    Welcome to the forum.
    Don't use a PL/SQL type, but an SQL type.
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:2270447621346#tom3041776036531
    Do a search on ORA-22905 on this forum for more examples.

  • Row Level PPR in Advanced Table with Add More Rows Button

    <br>
    I have programmatically fired PPR event on MessageChoice. But it is in Advanced Table with
    Add More Rows Button. When the value is changed in MessageChoice I Show/Hide Custom LOV
    through SPEL like this ${oa.BioEmployeePVO.EmpManagerRender} .
    But it is <b>hiding the all the ROWS</b> not just the row where the value has been changed.
    I even tried with this code and get NULL for rowReference.
    String rowReference = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
    In Processrequest()
    String pageName = pageContext.getRootRegionCode();
         Hashtable params = new Hashtable (1);
         params.put ("param1", pageName);
         Hashtable paramsWithBinds = new Hashtable(1);
        paramsWithBinds.put ("param2",new OADataBoundValueFireActionURL (mcb, "{$AttendeeType}"));
        mcb.setFireActionForSubmit ("empPositionChange", params, paramsWithBinds,false, false);
    In ProcessFormRequest() {
    if ("empPositionChange".equals(pageContext.getParameter(OAWebBeanConstants.EVENT_PARAM)))   
          String rowReference = pageContext.getParameter("param2");
        //    String rowReference = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
         Serializable[] parameters = { rowReference };
          am.invokeMethod("handlePositionChangeEvent", parameters);
    <br>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    HI Kumar,
    Answer to your last post is "yes".
    Now to your doubt regarding the code:
    Hi Anna
    I am trying to understand your code.
    FireAction firePartialAction = new FirePartialAction("fireHideEvent"+(i/noOfTlaColSpan));
    HideImgBean.setAttributeValue(PRIMARY_CLIENT_ACTION_ATTR,firePartialAction);
    1. What is this i/noOfTlaColSpan ?
    :)Forget abt this in your case it should be the event name which u r firing and capturing the it in the PFR.
    Like FireAction firePartialAction = new FirePartialAction("YOurEventName");
    and in PFR u can capture tht as:
    if("YOurEventName".equals(pageContext.getParameter(EVENT_PARAM)))
    //your logic to invoke AM method
    2. I believe this HideImgBean would be MessageChoice for me?
    :)Yep ur right
    3. This brcdOhInventoryViewUpdateVOImpl would be the Custom PVO(Extending Seeded Base VO)
    I create by adding the transient attributes?
    :)Yep ur right
    4. I cannot understand this code. Could you explain.
    :)Please look at my comments in some of the lines .I have explained wht i am doing
    if(updateIter==null)
    updateIter[0]= invViewVO.createRowSetIterator("updateIter");//This initViewVo should be ur custom VO object
    if(cnt>0)
    updateIter[0].setRangeStart(0);
    updateIter[0].setRangeSize(cnt);
    for(int i=0;i<cnt;i++)
    row = (brcdOhInventoryViewUpdateVORowImpl)updateIter[0].getRowAtRangeIndex(i);
    String selectFlag=(String)row.invokeMethod("getPartNumber");//This getPartNuber should be replaced by the Prim Key inoke methd of ur VO
    if(RowID.equals(selectFlag))
    //This is my logic to set the transient attributes based on the msgChoiceBean value ..u have to pass the value when u invoke this method
    if(reserveMethod.equals("BINARY"))
    System.out.println("In Binary");
    Boolean bVal= new Boolean("false");
    Serializable sr[]={bVal};
    Class []methodParamTypes = { bVal.getClass() };
    row.invokeMethod("setshowreservetxt",sr,methodParamTypes);
    Boolean bVal1= new Boolean("true");
    System.out.println("bVal1"+bVal1);
    Serializable sr1[]={bVal1};
    Class []methodParamTypes1 = { bVal1.getClass() };
    row.invokeMethod("setShowreservemsgchoice",sr1,methodParamTypes1);
    break;
    In my AM I am doing this. Am i doing right?:)Yep u r right
    BioPrescribersPVO is the custom VO(extending seeded base VO).
    public void handlePositionChangeEvent(String param)
    OAViewObject vo = (OAViewObject)findViewObject("BioPrescribersPVO");
    OARow row = (OARow)findRowByRef(rowReference);
    if (row != null)
    String position = (String)row.getAttribute("AttendeeType");
    if (("PRESCRIBER".equals(position)) )
    // BioEmpManagerRender is the transient attribute in BioPrescribersPVO.
    row.setAttribute("BioEmpManagerRender", Boolean.TRUE);
    row.setAttribute("BioPresManagerRender", Boolean.FALSE);
    else
    row.setAttribute("BioEmpManagerRender", Boolean.FALSE);
    row.setAttribute("BioPresManagerRender", Boolean.TRUE);
    } // end handlePositionChangeEvent()
    // Initializing the custom VO
    /*No need to initialize the VO because this is not a PVO(Propeties View object)
    U r just using the existing VO and tht vo shloud have a primary key.Tht way u can match the rowref u r getting with the actual row from the View object*/
    public void init()
    OAViewObject appPropsVO = (OAViewObject)getBioPrescribersPVO();
    if (appPropsVO != null)
    if (appPropsVO.getFetchedRowCount() == 0)
    appPropsVO.setMaxFetchSize(0); appPropsVO.executeQuery();
    appPropsVO.insertRow(appPropsVO.createRow());
    OARow row = (OARow)appPropsVO.first();
    row.setAttribute("RowKey", new Number(1));
    handlePositionChangeEvent("");
    } // end init()
    Thanks
    Anna

  • Joining tables with SQL in Crystal XI

    I am new to Crsytal Reports. I want to join 2 tables using a formula, which I am trying to do in SQL. I created a simple test report and I can get it to work if I don't put any fields on the report from the joined table.  ie  -  if I just use fields from "sal-rep" the report works.  As soon as I add a field from "freight" (my joined table) the report will not display anything.  (but I don't get any error messages - just a blank report).  Here is my SQL: 
    SELECT "sal-rep"."full-name","sal-rep"."invoice-nbr","freight"."misc-charge-ammount"  FROM   "PUB"."sal-rep" INNER JOIN "PUB"."FREIGHT" ON ("sal-rep"."invoice-nbr"="freight"."invoice-nbr")  WHERE  "sal-rep"."invoice-nbr"='0000189957'

    I got it to work!!!   This is the SQL I used -
    SELECT "sal_rep"."full-name", "sal_rep"."invoice-nbr", "freight"."misc-charge-ammount", "freight"."invoice-date"
    FROM   "PUB"."freight" "freight" INNER JOIN "PUB"."sal-rep" "sal_rep" ON ("freight"."invoice-nbr"="sal_rep"."invoice-nbr") AND ("freight"."invoice-date"="sal_rep"."inv-date")
    WHERE  "sal_rep"."invoice-nbr"='0000189957'
    Now when I look at the Table used in Database expert it lists -  Command and Freight.
    Before it was listing Command and Sal-Rep. 
    Not sure I understand why, but at least it's working.
    thanks for your help - really appreciated!

  • Can we join table with structure

    Hi
    i have taken fields from Plaf table and some fields from structures so now i want to join that how can i join.
    Is there any option?
    regards

    Hi,
    structure dont have any data base table associated with them so they dont have any data.
    that's why we cannot join structure witha table but we can include a structure within any table.
    Sytex to include structure in ztable:
    fieldname     data element.
    .include        struname
    hope it will ans ur query.
    Thanks
    Rajesh Kumar

  • Join table with an object type

    Hi,
    I would like ot know how to join a table with another table having an object type as a column value.
    For ex:
    Create type add_obj as object (st varchar2(10), city varchar2(10), zip varchar2(10));
    Table A
    Cust_id number
    cust_address add_obj
    Table B
    Cust_id number
    order_id number
    I want to select the complete address for each order.
    Is this the correct way to do this select:
    Select o.order_id, c.customer_id, c.cust_address.st, c.cust_address.city, c.cust_address.zip
    from table A c, table B o;
    Any leads is appreciated. Thanks in advance.

    >
    unfortunately with a crashed Oracle db I could try nothing.... Forums are for getting help and offering help in times of need.
    Will take your advice some other time. Now need help on how to select the address city, st and zip along with the order_id.
    >
    Ah - I understand - you mean before your class is over.
    Unfortunately with a crashed Oracle db you will not know if our advice is correct or not since you won't be able to test it.
    So I will offer advice some other time. Now need to get some fresh air and a hot cup of coffee.
    Let us know when you DB is back up and you have run your tests. Then if you still have any questions other forum members may decide to help you. Well - if their database is up and running that is.

  • Many to many join table with different column names

    Hi have a joint table with different column names as foreign keys in the joining
    tables...
    e.g. i have a many to many reltnshp btwn Table A and Table B ..and join table
    C
    both have a column called pk.
    and the join table C has columns call fk1 and fk2
    does cmd require the same column name in the join table as in the joining table?
    are there any workarounds?
    thanks

    HI,
    No, the foreign key column names in the join table do not have to match the primary
    key names in the joined tables.
    -thorick

  • Drop a table with triggers

    Dear All,
    I have a script which creates tables and triggers and drop the tables.
    I want to know if the triggers are dropped automatically when we drop the tables and when we create the tables what is the name of the tablespace that they are created in ?
    thank you in advance for your reply

    Triggers are dropped automatically when you drop the associated table.
    SQL> create table a (id number);
    Table created.
    SQL> create trigger trga before insert on a for each row
      2  begin
      3  null;
      4  end;
      5  /
    Trigger created.
    SQL> select trigger_name from user_triggers where table_name = 'A';
    TRIGGER_NAME
    TRGA
    SQL> drop table a;
    Table dropped.
    SQL> select trigger_name from user_triggers where table_name = 'A';
    no rows selected

  • How can i join table with multiple colums

    This is my Data-----------------------------------------------------DECLARE @StockIn TABLE
    InID INT ,
    StockID INT ,
    InQty DECIMAL(16, 2) ,
    Price DECIMAL(16, 2) ,
    tranDate DATE ,
    running INT
    DECLARE @StockOut TABLE
    OutID INT ,
    StockID INT ,
    OutQty DECIMAL(16, 2) ,
    lineid INT ,
    tranDate DATE
    INSERT INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES ( 1, 1, 15, 430, '2014-10-09', 1 ),
    ( 2, 1, 10, 431, '2014-10-10', 2 ),
    ( 3, 1, 15, 432, '2015-02-02', 3 ),
    ( 4, 2, 15, 450, '2014-08-05', 1 ),
    ( 5, 2, 6, 450, '2014-10-01', 2 ),
    ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES ( 1, 1, 20, 2, '2014-10-11' ),
    ( 2, 1, 10, 4, '2014-10-12' ),
    ( 3, 2, 12, 8, '2014-11-01' ),
    ( 4, 2, 3, 8, '2014-11-02' );--------------------------------------------------------------------This is my query for calculate the total remaining of stock of any stockID--------------------------------------------------------------------                    WITH  RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select 
     StockID, InQty  AS QTY , Price 
    , SUM(InQty) over (PARTITION BY StockID order by tranDate ,  inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY  tranDate ,  inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn  )  A   -- runing stockID in stock order by tranDate
    ) , TotalOut as ( 
    SELECT    StockID ,  Sum(OutQty) AS QTY
    FROM            @StockOut 
       GROUP BY StockID  -- Sum of outQty group by StockID
    ) ,  GrandTotal as 
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate  from 
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID 
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate  , rt.QTY  -- running OutQty out of inQty of any stockID
    ) Select * from GrandTotal order by stockID ------------------------------------------------------------
    This query is run the total remaining of stock exactly right. But if i try to get the OutQty of stockID of any Line (lineid)The query duplicate data. this is Example------------------------------------------------------------                    DECLARE @StockIn TABLE
          InID INT ,
          StockID INT ,
          InQty DECIMAL(16, 2) ,
          Price DECIMAL(16, 2) ,
          tranDate DATE ,
          running INT
    DECLARE @StockOut TABLE
          OutID INT ,
          StockID INT ,
          OutQty DECIMAL(16, 2) ,
          lineid INT ,
          tranDate DATE
    INSERT  INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES  ( 1, 1, 15, 430, '2014-10-09', 1 ),
            ( 2, 1, 10, 431, '2014-10-10', 2 ),
            ( 3, 1, 15, 432, '2015-02-02', 3 ),
            ( 4, 2, 15, 450, '2014-08-05', 1 ),
            ( 5, 2, 6, 450, '2014-10-01', 2 ),
            ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT  INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES  ( 1, 1, 20, 2, '2014-10-11' ),
            ( 2, 1, 10, 4, '2014-10-12' ),
            ( 3, 2, 12, 8, '2014-11-01' ),
            ( 4, 2, 3, 8, '2014-11-02' );
    WITH  RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select 
     StockID, InQty  AS QTY , Price 
    , SUM(InQty) over (PARTITION BY StockID order by tranDate ,  inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY  tranDate ,  inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn  )  A  
    ) , TotalOut as ( 
    SELECT    StockID ,  Sum(OutQty) AS QTY , lineid -- Group by stockID of any lineidFROM            @StockOut 
       GROUP BY StockID   , lineid
    ) ,  GrandTotal as 
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate , lineid from 
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID 
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate  , rt.QTY   , lineid
    ) Select * from GrandTotal order by stockID ----------------------------------------------How can i running the total out (OutQty*price) of any lineid

    Check this query, the date is excluded because it cannot return the result you want with and it will not be of any value to read the date like that in such a query:
    DECLARE @StockIn TABLE
    InID INT ,
    StockID INT ,
    InQty DECIMAL(16, 2) ,
    Price DECIMAL(16, 2) ,
    tranDate DATE ,
    running INT
    DECLARE @StockOut TABLE
    OutID INT ,
    StockID INT ,
    OutQty DECIMAL(16, 2) ,
    lineid INT ,
    tranDate DATE
    INSERT INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES ( 1, 1, 15, 430, '2014-10-09', 1 ),
    ( 2, 1, 10, 431, '2014-10-10', 2 ),
    ( 3, 1, 15, 432, '2015-02-02', 3 ),
    ( 4, 2, 15, 450, '2014-08-05', 1 ),
    ( 5, 2, 6, 450, '2014-10-01', 2 ),
    ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES ( 1, 1, 20, 2, '2014-10-11' ),
    ( 2, 1, 10, 4, '2014-10-12' ),
    ( 3, 2, 12, 8, '2014-11-01' ),
    ( 4, 2, 3, 8, '2014-11-02' );
    WITH RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select
    StockID, InQty AS QTY , Price
    , SUM(InQty) over (PARTITION BY StockID order by tranDate , inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY tranDate , inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn ) A
    ) , TotalOut as (
    SELECT StockID , Sum(OutQty) AS QTY , lineid -- Group by stockID of any lineid
    FROM @StockOut
    GROUP BY StockID , lineid
    ) , GrandTotal as
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate , lineid from
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate , rt.QTY , lineid
    ) Select Distinct StockID,(select sum(original) from GrandTotal G where G.lineid = GrandTotal.lineid) as original,(select sum(QTY) from GrandTotal G where G.lineid = GrandTotal.lineid) as QTY,
    (select sum(Price) from GrandTotal G where G.lineid = GrandTotal.lineid) as Price, (select sum(Ending) from GrandTotal G where G.lineid = GrandTotal.lineid) as Ending,lineid from GrandTotal
    order by stockID
    the result will be:
    StockID original QTY Price Ending lineid
    1 25.00 20.00 863.00 8635.0000 2
    1 40.00 30.00 1293.00 12940.0000 4
    2 21.00 21.00 902.00 9480.0000 8
    Fouad Roumieh

  • Updating Table with Triggers causes Raptor to Hang.

    Received an Error Window
    ORA-01000 Max Open Cursors Exceeded 1000
    Vendor Code 100
    This was displayed when updating a data value in a table which spawned a couple of Triggers, a before, after, and after statement trigger. What the Trigger does is when an Exchange Rate for a Date (one row), is changed the exchage_rate for every receipt is updated. The size of the table are in test and there are 100 receipts. The Echange Rate table has one record for every day between 01-JAN-2000 and 31-DEC-2050 (365.25*50) Rows. The open_cursors param in init file is 1000. Have done various scenarios and everything works fine from sqlplus. Hangs with message in Raptor, and have to kill process in windows..
    When run in Sqlplus no problem with update.

    I had the same problem but without triggers. I only changed some values in different records (always automatically commited) and after the third change I got this error message. At the same time I was connected with TOAD to the databse and there was no problem to change the data - so it doesn't look like a database problem.
    UPDATE "BLATABLE"."KEYS" SET "BLAVALUE" = "abcdef" WHERE ROWID = 'AAA2c1AADAAAHa5AAH' AND ORA_ROWSCN = '7738949481842'
    One error saving changes to table "BLATABLE"."KEYS":
    Row 6: ORA-01000: maximum open cursors exceeded

  • Join table with additional state

    I have two entities:
    A: @Id String acronym;
    B: @Id String name;
    and I need to create a relationship between these tables adding a new attribute:
    @Entity
    @SecondaryTables( {
              @SecondaryTable(name = "A", pkJoinColumns = @PrimaryKeyJoinColumn(name = "A_ACRONYM", referencedColumnName = "acronym")),
              @SecondaryTable(name = "B", pkJoinColumns = @PrimaryKeyJoinColumn(name = "B_NAME", referencedColumnName = "name")) })
    public class C implements Serializable {
         private static final long serialVersionUID = PujAbstractEntity.serialVersionUID;
         @Id
         @Column(name="acronym")
         private String acronym;
         @Id
         @Column(name="name")
         private String name;
    ERROR:
    [exec] Exception Description: An incomplete @PrimaryKeyJoinColumns was specified on the annotated element [class com.kenai.puj.arena.model.entity.PujInstitutionRoles]. When specifying @PrimaryKeyJoinColumns for an entity that has a composite primary key, a @PrimaryKeyJoinColumn must be specified for each primary key join column using the @PrimaryKeyJoinColumns. Both the name and the referencedColumnName elements must be specified in each such @PrimaryKeyJoinColumn.
    ????? any tip ?

    Thanks but I am still facing problems...
    --------- PujInstitutionEntity:
    @Entity
    public class PujInstitutionEntity extends PujAbstractRootEntity {
         @Id
         @Column(length = 20)
         private String acronym;
    --------- PujCompetitionEntity:
    @Entity
    public class PujCompetitionEntity extends PujAbstractRootEntity {
         @Id
         @Column(length = 12)
         private String name;
    --------- PujInstitutionRoles (the mapping):
    @Entity
    @IdClass(PujInstitution_Roles_ID.class)
    public class PujInstitutionRoles extends PujAbstractEntity {
         @ManyToOne
         @PrimaryKeyJoinColumn(name = "INSTITUTION_ACRONYM", referencedColumnName = "acronym")
         private PujInstitutionEntity institution;
         @ManyToOne
         @PrimaryKeyJoinColumn(name = "COMPETITION_NAME", referencedColumnName = "name")
         private PujCompetitionEntity competition;
    ---------- The deployment failure:
    [exec] Exception Description: Predeployment of PersistenceUnit [arenapuj] failed.
    [exec] Internal Exception: Exception [EclipseLink-7150] (Eclipse Persistence Services - 2.0.0.v20091009-r5515): org.eclipse.persistence.exceptions.ValidationException
    [exec] Exception Description: Invalid composite primary key specification. The names of the primary key fields or properties in the primary key class [com.kenai.puj.arena.model.entity.PujInstitution_Roles_ID] and those of the entity bean class [class com.kenai.puj.arena.model.entity.PujInstitutionRoles] must correspond and their types must be the same. Also, ensure that you have specified ID elements for the corresponding attributes in XML and/or an @Id on the corresponding fields or properties of the entity class.

Maybe you are looking for