我想用存储在另一个表中的计数器更新表列,该计数器在每次更新时递增。一切正常。但是,如果我将计数器重置为表中已经存在的新数字以进行更新,例如7;在更新过程中,它将找到我们在第一个循环中更新的7,并将其与其他值7一起更新。有没有办法跳过已经更新的值,只更新那些没有更新的值?我正在考虑添加带有标志的列以跟踪已更新的行;我在更新后将其删除。但是,我认为可能会有更好的方法。有任何想法吗?这是我目前拥有的:
/**counter table**/
create table ctl (cid int)
insert into ctl values (1)
/**table to update**/
create table tbl1(tid int)
insert into tbl1 (tid)
values(1),(1),(1),(1),(2),(3),(3),(3),(3),(3),(4),(5),(6),(7),(7)
/**temp table**/
select tid into #tmptbl from tbl1
declare @tidNum int
declare @cctl int
select @cctl = (select cid from ctl)
while exists (select tid from #tmptbl)
begin
select @tidNum = (select top 1 tid from #tmptbl order by tid asc)
update tbl1 set tid=@cctl where tid=@tidNum
select @cctl=@cctl+1
update ctl set cid=@cctl
delete #tmptbl where tid=@tidNum
end
select * from tbl1
drop table #tmptbl
/**counter table**/
create table ctl (cid int)
insert into ctl values (1)
/**table to update**/
create table tbl1(tid int)
insert into tbl1 (tid)
values(1),(1),(1),(1),(2),(3),(3),(3),(3),(3),(4),(5),(6),(7),(7)
go
begin transaction
declare @foo table(cid int);
declare @base int;
update ctl
set cid = cid + (select count(distinct tid) from tbl1)
output deleted.cid into @foo(cid);
select @base = cid
from @foo;
update t
set tid = addme + thebase
from
(
select tid, dense_rank() over(order by tid)-1 as addme, @base as thebase
from tbl1
) as t
--error handling goes here
commit transaction
go
select *
from tbl1;
update ctl
set cid = 4;
go
begin transaction
declare @foo table(cid int)
declare @base int
update ctl
set cid = cid + (select count(distinct tid) from tbl1)
output deleted.cid into @foo(cid);
select @base = cid
from @foo
update t
set tid = addme + thebase
from
(
select tid, dense_rank() over(order by tid)-1 as addme, @base as thebase
from tbl1
) as t
--error handling goes here
commit transaction
go
select *
from tbl1;
go