3.12 Implementing Priority Queues3.12.1 ProblemYou need to implement priority-based queues. In our example, the higher the purity index, the higher the priority. For these queues, you want to implement standard operations such as TOP, ENQUEUE, or DEQUEUE. 3.12.2 SolutionAs with stacks and regular queues, we can implement the priority queue in the ProductionLine table. 3.12.2.1 TOP function in SQLSELECT TOP 1 * FROM ProductionLine ORDER BY Purity DESC 3.12.2.2 DEQUEUE function in SQLCREATE PROCEDURE dequeue AS DECLARE @id INTEGER SELECT TOP 1 @id=ContainerId FROM ProductionLine ORDER BY Purity DESC SELECT * FROM ProductionLine WHERE @id=ContainerId DELETE FROM ProductionLine WHERE @id=ContainerId 3.12.2.3 ENQUEUE function in SQLCREATE PROCEDURE enqueue @Purity INTEGER AS DECLARE @id INTEGER SELECT TOP 1 @id=ContainerId FROM ProductionLine ORDER BY ContainerId DESC INSERT INTO ProductionLine(ContainerId,Purity) VALUES(@id+1, @Purity) SELECT * FROM ProductionLine WHERE ContainerId=@id+1 3.12.3 DiscussionPriority queues use a framework almost identical to that used for stacks and regular queues. The difference, again, is only in how the TOP function is implemented. When you adjust TOP to look at the queue in terms of priority, in our case at the Purity column, all the other pieces fall into place. The ENQUEUE function is the same as for regular queues. Except for the use of a priority-based TOP function, the DEQUEUE function is also the same as that for regular queues.
|