Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have 4 database tables all contain ItemId and Quantity.
The tables are:
1) Purchase
2) PurchaseReturn
3) Sale
4) SaleReturn
5) Stock

The stock table is empty has no data in it.
I would like to populate the stock on the base above mentioned tables.

How can I do this?

Please help me in this regard!

Thanks in advance!
Posted
Updated 16-Nov-11 22:16pm
v2

How do you do it? Presumably you know where the data is that you need to load the database, so I would suggest you write a program to copy it from where it is now to where you want it to be.
 
Share this answer
 
First thing you have to required all the Items which is purchase or sales table insert with stock zero into stock table.

now when you are purchase at that time you are insert record into the purchase table at that time you have to add purchase qty into current stock qty of that item and update stock table.

at the time of the purchase return , you have to deduct that qty from the current stock of that item and update that value into the stock table.

when you are sales at that time you have to deduct that qty from the current stock of that item and update that value into the stock table.

and at the time of the sales return, you have to add that qty from the current stock of that item and update that value into the stock table.
 
Share this answer
 
v2
The following SQL statement adds the products with the current stock value into the table.
SQL
INSERT INTO dbo.Stock SELECT ItemID, SUM(Quantity) AS TotalQuanity
                      FROM (SELECT ItemID, Quantity
                            FROM dbo.Purchase
                            UNION
                            SELECT ItemID, -Quantity
                            FROM dbo.PurchaseReturn
                            UNION
                            SELECT ItemID, -Quantity
                            FROM dbo.Sale
                            UNION
                            SELECT ItemID, Quantity
                            FROM dbo.SaleReturn) AS AllTransactions
                      GROUP BY ItemID

This assumes that the Quantity values in all the tables are positive.

First the four tables are put together using an UNION[^]. During this process the purchase returns and sales are made negative, as they will cause the stock to go down.

Next we perform a SUM[^] for each ItemID on the UNION results.

Finally the results of the SUM are inserted into the Stock table using the INSERT[^] statement.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900