SET @sql = '
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET DEADLOCK_PRIORITY 10
BEGIN TRAN
DECLARE @QuestionList TABLE(ID BIGINT,StudentCode NVARCHAR(50))
INSERT INTO @QuestionList(ID,StudentCode)
SELECT TOP '+CAST((@QuestionCount*@MinorQuestionCount) AS NVARCHAR(10))+' SS.ID,SS.StudentCode
FROM ['+@CourseID+'_SubjectiveScoreInfo] AS SS WITH(UPDLOCK,READPAST)
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 SS.MarkingStatusID = 1
AND SI.QuestionGroupCode=''' + @QuestionGroupCode + '''
AND (SI.MinorQuestionCount=0
OR SI.MinorQuestionID>0)
AND SS.MarkingStepID < 3
AND (HandledID1 IS NULL OR HandledID1 <> '''+ @HandledID +''')
AND (HandledID2 IS NULL OR HandledID2 <> '''+ @HandledID +''')
AND NOT EXISTS
(
SELECT TOP 1 1
FROM ['+@CourseID+'_SubjectiveScoreInfoFlag] WITH(NOLOCK)
WHERE AR = 0 AND ID = SS.ID
GROUP BY ID
HAVING ((SS.MarkingStepID <2 AND COUNT(*) >= 2) OR (SS.MarkingStepID = 2 AND COUNT(*) >= 3))
)
ORDER BY SS.StudentCode,SS.MajorQuestionID
INSERT INTO #TStudentCode(StudentCode,TaskHandledID,HandleStepId)
SELECT DISTINCT TOP '+CAST(@QuestionCount AS NVARCHAR(10))+' StudentCode, null ,0
FROM @QuestionList
INSERT INTO ['+@CourseID+'_SubjectiveScoreInfoFlag](AR,ID)
SELECT 0,ID
FROM @QuestionList
COMMIT TRAN
'
PRINT @sql
EXEC sp_executesql @sql