0

道歉,因为这可能是一个非常愚蠢的问题——我正在使用一个游标,它连接了一个大约 697K 行的临时表和一个返回 78K 行的函数。(我应该补充的是过去更糟糕的改进)。游标通过并匹配两个“表”中的两个值并更新第三个值。这需要6个小时左右。这是荒谬的。我们正在努力想办法提高效率。

任何和所有的建议表示赞赏。但我的询问是这样的——

在此处输入图像描述

它似乎正在返回如下所示的数据(在很多情况下为空信息)。我可以限制代码说哪里......数据不为空......但它不是它的返回 Null 它的空/不存在的行。我在想是否有办法排除这样的行,我们可能会限制我们的数据池。但我不完全知道这意味着什么。

declare @season int = 21

DECLARE @match varchar(55)
declare @perf_no int
declare @order_dt datetime

DECLARE   @price CURSOR
SET       @price = CURSOR FOR
SELECT    distinct match_criteria, perf_no, order_dt
FROM      #prices
OPEN      @price
FETCH NEXT
FROM      @price INTO @match, @perf_no, @order_dt
WHILE     @@FETCH_STATUS = 0
BEGIN

select  @match, @perf_no, @order_dt, x.price as 'amount'
from    #prices p
join    dbo.[LFT_GET_PRICES_Seasonal] (@season, @order_dt) x on p.perf_price_type = x.perf_price_type and p.zone_no = x.zone_no
where   match_criteria = @match and perf_no = @perf_no

FETCH NEXT
FROM @price INTO @match, @perf_no, @order_dt
END
CLOSE @price
DEALLOCATE @price

这是我们的函数返回的#prices 和# 示例。

价格

pkg_no  perf_no zone_no price_type  order_dt                    price   perf_price_type match_criteria
12      144     2707    1073        2018-09-03  00:00:00.000    NULL    115769          O5716788P1517Z2707
12      123     2707    1073        2018-09-03  00:00:00.000    NULL    115840          O5716788P1517Z2707
12      887     2707    1073        2018-09-03  00:00:00.000    NULL    115521          O5716788P1517Z2707

功能:

perf_price_type zone_no price   min_price   enabled editable_ind
115521          2678    12.00   12.00       Y       N
115521          2679    61.00   61.00       Y       N
115521          2680    41.00   41.00       Y       N

游标所做的是根据函数的价格更新#prices 表中的价格。(我们使用光标仅将其限制为某些性能/有限标准)。但我愿意接受建议。以及如何改善这一点的建议。

4

1 回答 1

0

You wrote you want to update the #price table with the results from the table valued function.
You can do that by using cross apply instead of a cursor. Since you didn't post proper sample data I have no way of testing my answer, but if it does what you need it should be doing that lightning-fast compared to a cursor.

DECLARE @season int = 21

UPDAET p
SET price = x.Price
FROM #Prices p
CROSS APPLY  
(
    SELECT * 
    FROM dbo.LFT_GET_PRICES_Seasonal(@season, order_dt) udf
    WHERE udf.perf_price_type = p.perf_price_type 
    AND udf.zone_no = p.zone_no
) x

SQL works best with a set based approach and not a procedural approach, which is why you want to avoid loops and cursors whenever possible and only use them as a last resort.

于 2018-09-06T18:27:37.613 回答