I make use of a temp table #temp to store the rows that required changes and identity column for the Pos.create table #data( ID int, Type varchar(10), Code varchar(10), Value varchar(10), Pos int)create table #temp( ID int, Value varchar(10), Pos int identity(1,1))delete #datainsert into #data(ID, Type, Code, Value, Pos)select 1, 'ADD', 'S1', NULL, NULL union allselect 2, 'ADD', 'S2', NULL, NULL union allselect 3, 'DELETE', 'S2', NULL, NULL union allselect 4, 'DELETE', 'S1', NULL, NULL union allselect 5, 'ADD', 'S3', NULL, NULL union allselect 6, 'ADD', 'S3', NULL, NULLinsert into #temp (ID, Value)select d.ID, case when d.Type = 'ADD' then 'A' else 'B' endfrom #data dwhere d.Code in (select x.Code from #data x where x.Code = d.Code and Type = 'ADD')and d.Code in (select x.Code from #data x where x.Code = d.Code and Type = 'DELETE')order by d.Code, d.Typeupdate #data set Value = t.Value, Pos = t.Pos from #data d inner join #temp t on d.ID = t.IDselect * from #datadrop table #datadrop table #temp
-----------------'KH'