mardi 26 janvier 2016

SQL SERVER While loop with nested If

I'm creating a stock market database and am really stumped that the following works correctly EXCEPT when the last selected price is equal to the incoming price (in which case the Select does not update). I've tried to simplify the code as follows, thanks in advance for feedback (I'm still noob):

Three tables: BuyOrders, SellOrders, MatchedOrders

StoredProcedure to process a NewBuyOrder:

 Insert NewBuyOrder to BuyOrders;

 While (NewBuyOrder.SharesRemaining > 0 )

      SELECT Top 1 FROM SellOrders WHERE SellOrders.Price <= NewBuyOrder.Price ORDER BY SellOrders.Price, SellOrders.TimePlaced;

             IF NewBuyOrder.SharesRemaining < SellOrders.SharesAvailable 
                   Update SellOrders.SharesAvailable = [difference];
                   Update BuyOrders = 0;
                   Insert into MatchedOrders;
                   Set NewBuyOrder.SharesRemaining = 0;
                   BREAK;

             ELSE
                   Update SellOrders = 0;
                   Update BuyOrders = [difference];
                   Insert into MatchedOrders;
                   Set NewBuyOrder.SharesRemaining = [difference];
                   CONTINUE;

Aucun commentaire:

Enregistrer un commentaire