任何人都可以帮我更有效地撰写此查询吗?
我有一个捕获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
答案 0 :(得分:1)
这样的事情:
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?