I am facing a very strange issue while working with while loop and table variable. Please find below my code in short.
A table variable - uniqueconsolidationkey, with following columns
- Rowid int identity primary
- DocumentId varchar value
- Consolidationkey.
First we inserting distinct consolidation value in our table variable.
It is a simple insert. Selecting data from another table.
Now, we apply a while loop through each row and update table variable with documentid. Please see the code below.
Rowno=1 and rowcount is no of row in our table variable
While(rowcount>rowno)
Begin
select @docid=some query to fetch milli seconds value plus some other varchar data
If(@prevdocid<>@docid)
Begin
Update @uniqueconsolidationkey
Set documentid=@docid
Where rowid=rowno
Set rowno=rowno+1
Set @prevdocid=@docid
End
End
Now the issue is Same documentid is assigned to different rows. I am not sure how.
And one more thing to note is, it happens for 4 rows alternatively. For ex. If row 385 has docid as ABC123 and row 386 has docid as DEF345 then at 387 docid again came as ABC123 and for 388 DEF345.
How this happened when we have all checks in place. This code run fine but sometime as I say once in five we see such issue.