Link to home
Start Free TrialLog in
Avatar of GRChandrashekar
GRChandrashekarFlag for India

asked on

Read Data before Commit ?

Hi I have a situation as follows

TABLE MONTHLYBILL [ NO INSERT, ALWAYS UPDATE ONLY]
MONTHLYBILL_ID [PK]
MEMBER_ID
AMOUNT


TABLE MONTHLYBILLDETAIL [INSERT / UPDATE]
MONTHLYBILLDETAIL_ID [PK]
MONTHLYBILL_ID [FK]
LEDGER_ID
AMOUNT



In a multi user environment, let us say user1 is trying to do as follows

1      UPDATE MONTHLYBILL SET AMOUNT = AMOUNT +100 WHERE MEMBER_ID=1
2      INSERT INTO MONTHLYDETAIL LEDGER_ID=1  AMOUNT= AMOUNT +75
3      INSERT MONTHLYDETAIL LEDGER_ID=1 AMOUNT = AMOUNT + 25


In a multi user environment, let us say user2 is trying to do as follows

1      UPDATE MONTHLYBILL SET AMOUNT = AMOUNT +100 WHERE MEMBER_ID=1
2      INSERT INTO MONTHLYDETAIL LEDGER_ID=1  AMOUNT= AMOUNT +75
3      INSERT MONTHLYDETAIL LEDGER_ID=3 AMOUNT = AMOUNT + 25

So in case 1, line 3, it should actually update since LEDGER_ID =1 is already present.

In case 2 lie 2, it should update since user1 has aleady inserted LEDGER_ID=1 but line 3 should be inseted since LEDGER_ID=3 is not present.

When so many users are operating how do i ensure that this logic works correctly ?



Avatar of XMarshall10
XMarshall10

If I have understood ur issue correctly, Irrespective of the fact that you are directly programming in the back end (using TSQL) or in the Front end (using C#), you should check the existing value in the LEDGER_ID field, and then decide whether to INSERT or UPDATE.

Also, in a multi user environment, using Multithreading approach from the Front end may be ideal using individual worker threads, and using thread synchronization for managing simultaneous DB operations.

-XM.
Avatar of GRChandrashekar

ASKER

Yes Problem is understood correctly. It is winform application with C# framework 2.0 Mutlithreading does not arise and it this action is performed from one form
But remember, checking LEDGER_ID when data is not commited
You should put all the DB logic into a Stored Procedure and also use Transactions (with locks) so that the in case of multi-user scenario no matter the order of their invocation the processing is always sequential.
ASKER CERTIFIED SOLUTION
Avatar of Franck Pachot
Franck Pachot
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi!
You might write a trigger on detail table to update AMOUNT in master table acording to value inserted in detail...

Something like:

create or replace trigger BLAH
before insert or update on MONTHLYBILLDETAIL
begin
 update MONTHLYBILL set amount=amount+nvl(:new.amount,0)-nvl(:old.amount,0);
end;

But instead of inserting/updating/merging into detail table I'd personally use a procedure to handle that,
use simple MERGE inside it, but in separate procedure, just to to handle tricky code on separate location...

Regards
Hrvoje