更新 SQL 服务器中获取的行
Update fetched rows in SQL Server
我有一个如下所示的存储过程:
alter procedure newProcedure
@take int,
@skip int
as
begin
set nocount on
declare @countRowNumbers int;
set @countRowNumbers = (select count(*) from TableA)
select *
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only
--update only fetched rows (first 100, or second 100)
-- update TableA set Status = 2
end
我有列状态,表示该行是否正在处理,所以当我抓取这 100 个文档时,我需要将该状态状态更新为 2。
我该怎么做?
alter procedure newProcedure
@take int,
@skip int
as
begin
set nocount on
declare @countRowNumbers int;
set @countRowNumbers = (select count(*) from TableA)
update tableA set status = 2 where ID in (
select a.ID
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only )
--update only fetched rows (first 100, or second 100)
-- update TableA set Status = 2
end
您应该能够为此使用可更新的 CTE:
with toupdate as (
select *
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only
)
update toupdate
set status = 2;
结合其他答案,首先使用可更新的CTE执行update
,然后使用output
子句捕获ID的更新,然后select
它们到return.
declare @SelectedId table (id int);
with toupdate as (
select *
from tableA a
order by a.ID
offset isnull(@skip,0) rows
fetch next isnull(@take, @countRowNumbers) rows only
)
update toupdate
set [status] = 2
output Inserted.id into @SelectedId;
select *
from tableA
where ID in (select id from @SelectedId)
order by ID;
我有一个如下所示的存储过程:
alter procedure newProcedure
@take int,
@skip int
as
begin
set nocount on
declare @countRowNumbers int;
set @countRowNumbers = (select count(*) from TableA)
select *
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only
--update only fetched rows (first 100, or second 100)
-- update TableA set Status = 2
end
我有列状态,表示该行是否正在处理,所以当我抓取这 100 个文档时,我需要将该状态状态更新为 2。
我该怎么做?
alter procedure newProcedure
@take int,
@skip int
as
begin
set nocount on
declare @countRowNumbers int;
set @countRowNumbers = (select count(*) from TableA)
update tableA set status = 2 where ID in (
select a.ID
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only )
--update only fetched rows (first 100, or second 100)
-- update TableA set Status = 2
end
您应该能够为此使用可更新的 CTE:
with toupdate as (
select *
from tableA a
order by a.ID
offset ISNULL(@skip,0) rows
fetch next ISNULL(@take, @countRowNumbers) rows only
)
update toupdate
set status = 2;
结合其他答案,首先使用可更新的CTE执行update
,然后使用output
子句捕获ID的更新,然后select
它们到return.
declare @SelectedId table (id int);
with toupdate as (
select *
from tableA a
order by a.ID
offset isnull(@skip,0) rows
fetch next isnull(@take, @countRowNumbers) rows only
)
update toupdate
set [status] = 2
output Inserted.id into @SelectedId;
select *
from tableA
where ID in (select id from @SelectedId)
order by ID;