|
if object_id ('tempdb .. # tmp') is not null
drop table #tmp GO
---- Create test data
declare @t table (S_DATA int, S_TIME int, S_ID int)
insert @t
select 3, 12, null union all select 2, 13, null union all select 2, 14, null union all select 1, 15, null union all select 4, 16, null union all select 5, 17, null union all select 3 , 18, null union all select 3, 19, null union all select 2, 20, null union all select 4, 21, null union all select 1, 22, null union all select 2, 23, null union all select 3, 24 , null union all select 5, 25, null union all select 3, 26, null union all select 2, 27, null union all select 6, 28, null union all select 2, 29, null union all select 3, 30, null union all select 4, 31, null union all select 1, 32, null union all select 1, 33, null union all select 2, 34, null union all select 5, 35, null union all select 2, 36, null union all select 3, 37, null union all select 4, 38, null union all select 1, 39, null union all select 2, 40, null union all select 3, 41, null
---- Update from top to bottom
declare @data int, @ flag int set @flag = 1
UPDATE @t SET
/ * Use @data as a flag for judging that S_DATA is continuously 4, 5, 6 invalid data
@data = case
when @data between 4 and 6 and S_DATA between 4 and 6 then 888 else S_DATA
end,
@flag =
case
when S_DATA between 1 and 3 then @flag
when S_DATA between 4 and 6 and @data <> 888 then @flag + 1
else 1
end,
S_ID =
case
when S_DATA between 4 and 6 then null
else @flag end
---- Generate temporary tables for bottom-up updates
select * into #tmp from @t order by S_TIME DESC
---- Update the temporary table from top to bottom (equivalent to updating the original table from bottom to top)
declare @mark bit
/ * Judgment flag used when updating S_ID * /
set @flag = 1
UPDATE #tmp SET
@mark =
case
when @mark = 1 then 1
else
case when S_DATA = 6 then 1 end
/ * If a row with S_DATA = 6 is encountered, subsequent rows are prohibited from being updated * /
end,
/ * Use @data as a flag for judging that S_DATA is continuously 4, 5, 6 invalid data
@data =
case
when @data between 4 and 6 and S_DATA between 4 and 6 then 888 else S_DATA
end,
@flag =
case
when S_DATA between 1 and 3 then @flag
when S_DATA between 4 and 6 and @data <> 888 then @flag + 1
when S_DATA between 4 and 6 and @data = 888 then @flag else 1
end,
S_ID =
case
when @mark = 1 then S_ID / * S_ID of the row before S_DATA = 6 when updating for the first time is no longer updated, keep the original value * / else
case
when S_DATA between 4 and 6 then null
else @flag
end
end
---- Update the S_ID of the original table
update a set S_ID = b.S_ID from @t as a
inner join #tmp as b on a.S_DATA = b.S_DATA and a.S_TIME = b.S_TIME
---- Check for updates
select * from @t
---- Clear test environment
drop table #tmp |
|