insert into #temp(ranking, newrownumb, [status]) select A.ranking,A.newrowNumb, case when a.newrowNumb = 1 THEN 'Sampling' when a.newrowNumb=2 and a.PreviousDiscrepancies='yes' THEN '1st Check' when a.newrowNumb=2 and a.PreviousDiscrepancies='no' THEN 'Skip' when b.[status]= '1st Check' THEN '2nd Check' when b.[status]='2nd Check' and a.PreviousDiscrepancies='yes' THEN '1st Check' when b.[status]='2nd Check' and a.PreviousDiscrepancies='no' THEN 'skip' when b.[status]='skip' THEN 'sampling' when b.[status]='sampling' and a.PreviousDiscrepancies='no' THEN 'skip' when b.[status]='sampling' and a.PreviousDiscrepancies='yes ' THEN '1st Check' else 'unknown' end as status from #q2 aLEFT join #temp b on b.newrowNumb = a.newrowNumb - 1 and a.ranking=b.ranking where a.ranking = @countsupplier and a.newrowNumb = @countrow