declare @PGuid varchar(50) declare @Count int declare myCur2 Cursor LOCAL for( select ParentRowGuid ,Count(*) as count from [BIMPM_ModelData].[dbo].[EquipmentEFile] where ExtendName = 'rfa' group by ParentRowGuid HAVING count(ID) >1) open myCur2 fetch next from myCur2 into @PGuid,@Count while(@@FETCH_STATUS=0) begin ---select * from [BIMPM_ModelData].[dbo].[EquipmentEFile] where ParentRowGuid = @PGuid and ExtendName = 'rfa' order by ID update [BIMPM_ModelData].[dbo].[EquipmentEFile] set [FirstVersionRowGuid] = t2.RowGuid from (select top 1 ID,RowGuid from [BIMPM_ModelData].[dbo].[EquipmentEFile] where ParentRowGuid = @PGuid and ExtendName = 'rfa' order by id) t2 where [BIMPM_ModelData].[dbo].[EquipmentEFile].ParentRowGuid = @PGuid update [BIMPM_ModelData].[dbo].[EquipmentEFile] set [IsMaxVersion] = 0 from (select top 1 ID,RowGuid from [BIMPM_ModelData].[dbo].[EquipmentEFile] where ParentRowGuid = @PGuid and ExtendName = 'rfa' order by id desc) t2 where [BIMPM_ModelData].[dbo].[EquipmentEFile].ParentRowGuid = @PGuid and [BIMPM_ModelData].[dbo].[EquipmentEFile].[IsMaxVersion] = 1 AND [BIMPM_ModelData].[dbo].[EquipmentEFile].RowGuid <> t2.RowGuid fetch next from myCur2 into @PGuid,@Count end close myCur2