Tsql 查询以更新rowNum

Tsql 查询以更新rowNum,tsql,Tsql,有人能帮我更有效地编写这个查询吗 我有一个捕获TCP流量的表,我想更新一个名为RowNumForFlow的列,它是该流中IP数据包的序列号。下面的代码工作正常,但速度很慢 declare @FlowID int declare @LastRowNumInFlow int declare @counter1 int set @counter1 = 0 while (@counter1 < 1) BEGIN set @counter1 = @counter1 + 1 -- 1) se

有人能帮我更有效地编写这个查询吗

我有一个捕获TCP流量的表,我想更新一个名为RowNumForFlow的列,它是该流中IP数据包的序列号。下面的代码工作正常,但速度很慢

declare @FlowID int
declare @LastRowNumInFlow int
declare @counter1 int
set @counter1 = 0

while (@counter1 < 1)
BEGIN
set @counter1 = @counter1 + 1   

-- 1)
select  top 1
        @FlowID = t.FlowID
from    Traffic t 
where   t.RowNumInFlow is null

if (@FlowID is null)
    break

-- 2)
set @LastRowNumInFlow = null

select  top 1
        @LastRowNumInFlow = RowNumInFlow
from    Traffic 
where   FlowID=@FlowID and RowNumInFlow is not null
order by ID desc

if @LastRowNumInFlow is null
    set @LastRowNumInFlow = 1
else
    set @LastRowNumInFlow = @LastRowNumInFlow + 1

update Traffic set RowNumInFlow = @LastRowNumInFlow
where ID = (select top 1 ID from Traffic where 
            flowid = @FlowID and RowNumInFlow is null)


END
运行查询后的表值示例:

ID FlowID RowNumInFlow 448923 44 1 448924 44 2 448988 44 3 448989 44 4 448990 44 5 448991 44 6 448992 44 7 448993 44 8 448995 44 9 448996 44 10 449065 44 11 449063 45 1 449170 45 2 449171 45 3 449172 45 4 449187 45 5 大概是这样的:

update
    T
set
    RowNumInFlow = @TheNumber
FROM
   (
    SELECT
       ID, 
       ROW_NUMBER() OVER (PARTITION BY FlowID ORDER BY ID) AS TheNumber
    FROM
       Traffic
   ) T
评论后:

update
    T1
set
    RowNumInFlow = TR.TheNumber
FROM
   Traffic T1
   JOIN 
   (
    SELECT
       ID, 
       ROW_NUMBER() OVER (PARTITION BY FlowID ORDER BY ID) AS TheNumber
    FROM
       Traffic
   ) TR ON T1.ID = TR.ID
   WHERE
       T1.RowNumInFlow IS NULL --like this?

看起来很好。分割条款似乎正是我所需要的。有没有办法只更新尚未填充的行?这很有效:我添加了where子句。这比我以前的查询快大约100000倍:恭喜!其中Traffic.ID=T.ID