并发查询和更新问题,为了防止同一条记录被多次返回,使用了别一张表记录已经被返回这的记录ID,不论结构是否合理,因为修改代价太大,只能优化SQL语句,等待高手。
代码如下:
BEGIN TRAN
--不加这句不会死锁,但会出现同一条记录被重复取出 SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
INSERT INTO #TStudentCode(StudentCode,TaskHandledID,HandleStepId) SELECT TOP 1 SS.StudentCode,null,0 FROM [01_SubjectiveScoreInfo] AS SS INNER JOIN SubjectiveItemInfo AS SI ON SS.TestCode=SI.TestCode AND SS.MajorQuestionID=SI.MajorQuestionID AND SS.MinorQuestionID=SI.MinorQuestionID WHERE SS.TestCode=''' + @TestCode + ''' AND SI.QuestionGroupCode=''' + @QuestionGroupCode + ''' AND (SI.MinorQuestionCount=0 OR SI.MinorQuestionID>0) AND NOT EXISTS ( SELECT TOP 1 1 FROM [01_SubjectiveScoreInfoFlag] WHERE ID = SS.ID ) INSERT INTO [01_SubjectiveScoreInfoFlag](ID) SELECT SS.ID FROM [01_SubjectiveScoreInfo] AS SS INNER JOIN SubjectiveItemInfo AS SI ON SS.TestCode=SI.TestCode AND SS.MajorQuestionID=SI.MajorQuestionID AND SS.MinorQuestionID=SI.MinorQuestionID WHERE SS.TestCode=''' + @TestCode + ''' AND SI.QuestionGroupCode=''' + @QuestionGroupCode + ''' AND (SI.MinorQuestionCount=0 OR SI.MinorQuestionID>0) AND SS.StudentCode = (SELECT TOP 1 StudentCode FROM #TStudentCode) COMMIT TRAN
主表为:[01_SubjectiveScoreInfo],已查询过的ID记录表为:[01_SubjectiveScoreInfoFlag] 。
1 保持事务短小
2 查询时with(updlock,readpast) 锁定查询的记录
我试试
多谢,应该搞定了。原来要用排它锁才能不死锁。