ALTER PROCEDURE sp_nameASBEGIN SET NOCOUNT ON; SELECT r.RecordID AS CallID, 'MFS' AS CallType, a.Login AS AgentUID, 0 as Scored, r.RecStop as CallDateTime INTO #tmpCallScores FROM recording r INNER JOIN history h ON r.historyid = h.historyid INNER JOIN agent a ON h.AgentID = a.AgentID WHERE r.VMExtension = 0 AND h.CRC = 'NOTE' and h.talktime > 90 and datediff(hour, recstop, GetDate()) <= 24 and not exists (select callid from CallScores where CallID = r.RecordID) declare cur cursor for select AgentUID from #tmpCallScores group by AgentUID declare @login nvarchar(10) open cur fetch next from cur into @login while @@fetch_status = 0 begin INSERT INTO CallScores (CallID, CallType, AgentUID, Scored, CallDateTime) SELECT TOP 4 CallID, CallType, AgentUID, Scored, CallDateTime FROM #tmpCallScores WHERE AgentUID = @login ORDER BY Rand() fetch next from cur into @login endENDGO