简体   繁体   中英

How do I set isolation levels so that once one transaction completes the inserted data is available to another transaction?

I have the following tables (greatly simplified):

Jobs: JobId, JobState
Data: DataId
JobsData: JobId, DataId

the idea for JobsData is that any item in Data can be associated to one or more item in Jobs and each item in Jobs can have one or more item from Data associated with it.

Now I have two transactions:

-- TRAN1
BEGIN TRAN
INSERT INTO Data VALUES (NewDataId)
INSERT INTO Jobs VALUES (NewJobId, StateInitial)
INSERT INTO JobsData VALUES (NewDataId, NewJobId)
UPDATE Jobs SET JobState=StateReady WHERE JobId=NewJobId
COMMIT TRAN

-- TRAN2
DECLARE @selectedId;
SELECT TOP (1) @selectedId=JobId FROM Jobs WITH (UPDLOCK, READPAST) WHERE JobState=StateReady
IF @selectedId IS NOT NULL
    SELECT DataId FROM JobsData WHERE JobId = @selectedId

The code with the locking hints comes from this answer . Its purpose is to have multiple TRAN2 instances running in parallel and never getting the same JobId .

That code has been working fine with SQL Server (default isolation level READ_COMMITTED ) but in SQL Azure TRAN2 sometimes works incorrectly - the first SELECT yields a non-null JobId , but the second SELECT yields and empty resultset. I assume this is because the default isolation level in SQL Azure is READ_COMMITTED_SNAPSHOT .

I want to make minimum changes to get my problem resolved - so that TRAN2 either retrieves null in the first SELECT or retrieves the right result set in the second SELECT .

Which of the table hits do I apply to which of the SQL statements I have?

For a starter, if you want queues in Azure, use Azure Queues or Service Bus Queues .

If you insist on implementing queues over relations, use the pattern from Using Tables as Queues . Specifically:

  • do not use state fields instead of event queues ('Ready' is a record in your jobs queue, an event , not a state on the job).
  • dequeue using DELETE ... WITH OUTPUT ...

Trust me on this one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM