gpt4 book ai didi

TSQL 在游标循环中更快

转载 作者:行者123 更新时间:2023-12-03 03:33:10 25 4
gpt4 key购买 nike

建立查询。

单个查询如下所示,运行时间为 7.0 秒。它确实返回正确的答案。需要根据一定的条件对行进行计数,然后得到最大计数。我的问题是这个独立查询的性能。包含在游标中的相同查询需要 0.15 秒。在游标中,查询计划有很大不同。如何使独立查询运行得更快?

使用提示能够使独立计划看起来像光标计划,并解决了速度问题。

修复了查询:(由于 OPTION 失败,并未完全修复)

select max(list.match) as 'max'
from
(
SELECT
count(*) as 'match'
FROM [docSVenum1] with (nolock)
INNER LOOP JOIN [FTSindexWordOnce] as w1 with (NOLOCK, FORCESEEK)
ON [docSVenum1].sID = w1.[sID] and [docSVenum1].[enumID] = '142'
INNER HASH JOIN [FTSindexWordOnce] as w2 with (NOLOCK)
ON w1.wordID = w2.wordID and w2.[sID] = '2'
GROUP BY W1.[sID]
-- OPTION (HASH GROUP)
) as list;

问题查询:

select getdate();
go
select max(list.match) as 'max'
from
(
SELECT
count(*) as 'match'
FROM [FTSindexWordOnce] as w1 with (nolock)
INNER JOIN [docSVenum1] with (nolock)
ON [docSVenum1].sID = w1.[sID] and [docSVenum1].[enumID] = '142'
INNER JOIN [FTSindexWordOnce] as w2 with (nolock)
ON w1.wordID = w2.wordID AND w2.[sID] = '2'
GROUP BY W1.[sID]
) as list;
go
select getdate(); -- 7.0 seconds

我还需要针对多个值运行单个查询,并将其放入带有循环的游标中。我知道光标不好,但我不知道如何在没有光标的情况下做到这一点。

独立查询和循环内部查询都返回相同的正确答案。

令我惊讶的是,游标循环内完全相同的查询速度快了 40 倍。

DECLARE @sid int

DECLARE sID_cursor CURSOR FOR
SELECT top 80 sID
FROM docSVsys
WHERE sID = '2' -- actually I want to not have this and let it loop through all
-- when i built the loop i saw performance improvement
ORDER BY sID

OPEN sID_cursor

FETCH NEXT FROM sID_cursor
INTO @sID

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @sID

select max(list.match) as 'max'
from
(
SELECT
count(*) as 'match'
FROM [FTSindexWordOnce] as w1 with (nolock)
INNER JOIN [docSVenum1] with (nolock)
ON [docSVenum1].sID = w1.[sID] and [docSVenum1].[enumID] = '142'
INNER JOIN [FTSindexWordOnce] as w2 with (nolock)
ON w1.wordID = w2.wordID AND w2.[sID] = @sID
GROUP BY W1.[sID]
) as list

FETCH NEXT FROM sID_cursor
INTO @sID

END
CLOSE sID_cursor;
DEALLOCATE sID_cursor;
go
select getdate(); -- 0.15 seconds

最佳答案

使用提示能够使独立计划看起来像光标计划,并解决了速度问题。

修复了查询:(由于 OPTION 失败,并未完全修复)

select max(list.match) as 'max'
from
(
SELECT
count(*) as 'match'
FROM [docSVenum1] with (nolock)
INNER LOOP JOIN [FTSindexWordOnce] as w1 with (NOLOCK, FORCESEEK)
ON [docSVenum1].sID = w1.[sID] and [docSVenum1].[enumID] = '142'
INNER HASH JOIN [FTSindexWordOnce] as w2 with (NOLOCK)
ON w1.wordID = w2.wordID and w2.[sID] = '2'
GROUP BY W1.[sID]
-- OPTION (HASH GROUP)
) as list;

关于TSQL 在游标循环中更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com