SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Working with Queues in SQL Server


Working with Queues in SQL Server

Author
Message
Ahmad Alkilani
Ahmad Alkilani
Valued Member
Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)Valued Member (73 reputation)

Group: General Forum Members
Points: 73 Visits: 157
Comments posted to this topic are about the item Working with Queues in SQL Server
Adrian Hains
Adrian Hains
Mr or Mrs. 500
Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)Mr or Mrs. 500 (550 reputation)

Group: General Forum Members
Points: 550 Visits: 261
FYI - the OUTPUT clause is available in sql2k5 as well.
-a
Paul White
Paul White
SSC Guru
SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)

Group: General Forum Members
Points: 60412 Visits: 11396
Setup:

-- For the demo
USE tempdb;
GO
IF OBJECT_ID(N'dbo.WorkQueue', N'U')
IS NOT NULL
DROP TABLE dbo.WorkQueue;

IF OBJECT_ID(N'dbo.GetWorkItem', N'P')
IS NOT NULL
DROP PROCEDURE dbo.GetWorkItem;

IF OBJECT_ID(N'dbo.SetWorkItemComplete', N'P')
IS NOT NULL
DROP PROCEDURE dbo.SetWorkItemComplete;

-- Create table
CREATE TABLE dbo.WorkQueue
(
work_queue_id INTEGER IDENTITY(1,1) NOT NULL
PRIMARY KEY,
name VARCHAR(255) NOT NULL,
status_id TINYINT NOT NULL
CHECK (status_id IN (0, 1, 2)),
status_desc AS
ISNULL
(
CASE status_id
WHEN 0 THEN 'Unprocessed'
WHEN 1 THEN 'In progress'
WHEN 2 THEN 'Processed'
ELSE NULL
END,
'')
);

-- Add data to table
INSERT dbo.WorkQueue
(name, status_id)
SELECT 'A', 0 UNION ALL
SELECT 'B', 0 UNION ALL
SELECT 'C', 0 UNION ALL
SELECT 'D', 0 UNION ALL
SELECT 'E', 0 UNION ALL
SELECT 'F', 0 UNION ALL
SELECT 'G', 0 UNION ALL
SELECT 'H', 0 UNION ALL
SELECT 'I', 0 UNION ALL
SELECT 'J', 0 UNION ALL
SELECT 'K', 0;
GO
-- Index to help find unprocessed items
CREATE NONCLUSTERED INDEX nc1
ON dbo.WorkQueue (status_id);



Procedures:

CREATE PROCEDURE dbo.GetWorkItem
@WorkQueueID INTEGER OUTPUT
AS
BEGIN
SET NOCOUNT ON;

-- Allocate a work item and set it to in-progress
-- TODO: Add lock timeout and error handler
UPDATE Q
SET status_id = 1,
@WorkQueueID = work_queue_id
FROM (
SELECT TOP (1)
Q2.work_queue_id,
Q2.status_id
FROM dbo.WorkQueue Q2 WITH (UPDLOCK, READPAST, ROWLOCK)
WHERE Q2.status_id = 0
ORDER BY
Q2.work_queue_id ASC
) Q;

RETURN CASE WHEN @WorkQueueID IS NULL THEN 999 ELSE 0 END
END;
GO
CREATE PROCEDURE dbo.SetWorkItemComplete
@WorkQueueID INTEGER
AS
BEGIN
SET NOCOUNT ON;

-- Set the work item's status to complete
-- TODO: Add lock timeout and error handler
UPDATE Q
SET status_id = 2
FROM WorkQueue Q
WHERE Q.work_queue_id = @WorkQueueID
AND Q.status_id = 1;

RETURN CASE WHEN @@ROWCOUNT = 0 THEN 999 ELSE 0 END;
END;
GO


Test:

DECLARE @WorkItemID INTEGER,
@ReturnCode INTEGER;

-- Get a work item
EXECUTE @ReturnCode =
dbo.GetWorkItem @WorkItemID OUTPUT;

-- Show the record
SELECT rc = @ReturnCode,
*
FROM dbo.WorkQueue
WHERE work_queue_id = @WorkItemID;

-- Simulate processing delay
WAITFOR DELAY '00:00:03';

-- Set the work item to complete
EXECUTE @ReturnCode =
dbo.SetWorkItemComplete @WorkItemID;

-- Show the record
SELECT rc = @ReturnCode,
*
FROM dbo.WorkQueue
WHERE work_queue_id = @WorkItemID;

GO
DROP TABLE dbo.WorkQueue;
DROP PROCEDURE dbo.GetWorkItem;
DROP PROCEDURE dbo.SetWorkItemComplete;



Results:

rc work_queue_id name status_id status_desc
0 1 A 1 In progress
...
0 1 A 2 Processed


Allocation routine query plan: (compute scalars removed)




Paul White
SQLPerformance.com
SQLblog.com
@SQL_Kiwi
Attachments
Plan.gif (790 views, 5.00 KB)
HansVE
HansVE
SSC-Enthusiastic
SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)SSC-Enthusiastic (180 reputation)

Group: General Forum Members
Points: 180 Visits: 339
Much better article at http://rusanu.com/2010/03/26/using-tables-as-queues/
Bill Nicolich
Bill Nicolich
Say Hey Kid
Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)

Group: General Forum Members
Points: 661 Visits: 545
Hey folks. I recently built a system where users share a pool of work items and I too use a table-based queue. So I feel kind of familiar with some of the issues.

It seems to me that the proposed solution handles the initial concurrency problem well. There's no chance that two people will get the same open item in the queue. So it solves what I call the reservation problem. You want users to be able to reserve or lock an item.

However, another problem is getting disconnected. It's the "orphaned work item" issue. The calling app, if a web application, for instance - may drop the connection. Then a row may stay marked as processed/reserved and stay that way. In order to handle these situations, you either have to ensure that it doesn't happen up-front (sometimes not possible) - or have a way to identify rows not being worked by a user.

I've used the table-based method of reserving rows for a work queue with a web application front-end. There are occasions when a session end or the user gets disconnected. I handle the getting disconnected problem by programming the application "session end" event. In the event, I "un-mark" the row in question using the application. That works most of the time - but there are occasions when that event isn't called - and I then have to un-mark those rows another way.

Now, when that happens, there's the problem of identifying rows that have been marked as reserved but are not being handled by a current user. Due to this problem, I chose to do something slightly different than adding a flag column and using the query hints.

I created an additional history table for item reservations. I add a row when a work item is reserved by a user. It includes a session id, item id, expiration flag, start date and end date. The bi-temporal approach allows me to automatically "unlock" items within a specified period of time - such as a day.

It's actually nice to keep a history table for item reservations - and in some cases, it can help satisfy "chain of custody" requirements. It is also a way to handle the orphaned work item issue.

I welcome your thoughts and critiques. Thanks.

Bill Nicolich: www.SQLFave.com.
Daily tweet of what's new and interesting: AppendNow
noeld
noeld
SSC-Dedicated
SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)SSC-Dedicated (38K reputation)

Group: General Forum Members
Points: 38652 Visits: 2051
One more comment: The use of READPAST should be carefully considered for two reasons:
1. If you need to preserve the order you must exclude it
2. If you are using READ_COMMITED_SNAPSHOT ON at the database level and The transaction isolation level of the session is READ COMMITTED.


* Noel
Paul White
Paul White
SSC Guru
SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)SSC Guru (60K reputation)

Group: General Forum Members
Points: 60412 Visits: 11396
Bill Nicolich (4/5/2010)
...when that happens, there's the problem of identifying rows that have been marked as reserved but are not being handled by a current user.

A history table works well. For simple implementations, adding columns to the queue table to store the process/user identifier that owns the resource, and the time it acquired it, can work well (enough) too.



Paul White
SQLPerformance.com
SQLblog.com
@SQL_Kiwi
Bill Nicolich
Bill Nicolich
Say Hey Kid
Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)Say Hey Kid (661 reputation)

Group: General Forum Members
Points: 661 Visits: 545
Paul White NZ (4/5/2010)
Bill Nicolich (4/5/2010)
...when that happens, there's the problem of identifying rows that have been marked as reserved but are not being handled by a current user.

A history table works well. For simple implementations, adding columns to the queue table to store the process/user identifier that owns the resource, and the time it acquired it, can work well (enough) too.


When you match up a work item with a user, there are some considerations. What constitutes a user? In my case, a user was a unique session id from the web server. It wasn't a web farm situation. A user could have IE open with one session and FireFox open with another session - and these in my case should be handled separately. So if I just had just a "user id" matching things up in the table, I'd run into problems. So, that's why I added both a session id and a user id in the table.

Bill Nicolich: www.SQLFave.com.
Daily tweet of what's new and interesting: AppendNow
Eric Strickland
Eric Strickland
Grasshopper
Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)Grasshopper (17 reputation)

Group: General Forum Members
Points: 17 Visits: 9
For the Demo,

If doing this in 2008 and you just use the update "with (READPAST), If you do not move the Delay to before the commit Both sessions will pick up the same record.

Eric.
peleg
peleg
Ten Centuries
Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)Ten Centuries (1.1K reputation)

Group: General Forum Members
Points: 1073 Visits: 537
when i first looked at the title articles, i was sure it talkes about queues, that work in FIFO - first in -> first out.
but when i saw the row

SELECT TOP(1)
@work_queue_id = work_queue_id, @name = name
FROM
work_queue
WHERE processed_flag = 0


it dosen't ensure me that i will get the first available row from the table!
maybe it will be better to work with the Queue that the sql provides you, rather then using a table, and getting into situation where you find your self with looked rows and so on like Bill said.
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum







































































































































































SQLServerCentral


Search