使用Row_Number()和/或满足条件时的游标和中断更新记录集-SQL Server

问题描述 投票:-1回答:1

我有一个表,我想在其中更新CID列,直到找到另一个列值,其中EID =7。我按DESC顺序使用PID对表进行了排序。这是我的表结构。

enter image description here

更新后,表格将如下所示:

enter image description here

我基本上是想按CID对表进行重新排序,并希望更新最上面的行(设置CID = 1010),直到找到EID = 10为止。当EID = 10时,它将不更新下面的其余行,包括它,我尝试使用Row_Number()的原因是我的表包含不同且大量的CID,而且每个CID的EID值都不同,但是每个CID的EID =10。我尝试使用游标,使用Row_Number()进行排序,但我无法获取正确的数据。欢迎任何帮助。

sql sql-server tsql
1个回答
1
投票

您可以使用开窗功能,将发生的次数设为10,然后如下更新:

update t 
set t.cid = 1010 
from #table t join
( select *, sum(case when eid = 10 then 1 else 0 end) over(order by pid desc) rown from #table ) r
on t.PId = r.PId
and rown = 0

代码如下:https://rextester.com/GUW95636

© www.soinside.com 2019 - 2024. All rights reserved.