【问题标题】:Cursor updates all rows instead of one光标更新所有行而不是一行
【发布时间】:2014-06-21 15:41:39
【问题描述】:

我需要查看一个视图 (vRidesForPricing) 并将每一行与另一个视图 (vRidesDone) 的内容进行比较。

我正在搜索匹配项 - 如果 RidesDone 的当前行的 CompanyIDSourceIdDestinationIdRidesForPricing 中的这些字段匹配,那么我想用 @ 更新 RidesForPricing 987654329@RidesDone 的值(意思是如果在我只想拿它的价格并复制它之前发生完全相同的骑行)。

我写了一个游标,但它用相同的值更新了RidesForPricing 中的所有行。我错过了什么?任何帮助,将不胜感激。我正在使用 SQL Server 2008 R2。

DECLARE @CompanyID as int, @Date datetime, @SourceId as int, @DestinationId as int, @PriceOffice as nvarchar(250)

DECLARE @RidesForPricingCursor as CURSOR;
SET @RidesForPricingCursor = CURSOR FOR
SELECT CompanyID, Date, SourceId, DestinationId, PriceOffice
FROM dbo.vRidesForPricing
FOR UPDATE OF PriceOffice

OPEN @RidesForPricingCursor;
FETCH NEXT FROM @RidesForPricingCursor 
INTO @CompanyID, @Date, @SourceId, @DestinationId, @PriceOffice

CREATE TABLE #TEMP (CompanyID int, Date datetime, SourceId int, DestinationId int,
            PriceOffice nvarchar(250))

WHILE @@FETCH_STATUS = 0
BEGIN

INSERT INTO #TEMP
SELECT CompanyID, Date, SourceId, DestinationId, PriceOffice
FROM dbo.vRidesDone 
WHERE CompanyID = @CompanyID AND SourceId = @SourceId AND DestinationId = @DestinationId
ORDER BY Date

IF (SELECT COUNT(*) FROM #TEMP) > 0
SET @PriceOffice = (SELECT TOP 1 PriceOffice FROM #TEMP)

UPDATE vRidesForPricing 
SET PriceOffice = @PriceOffice WHERE CURRENT OF @RidesForPricingCursor

FETCH NEXT FROM @RidesForPricingCursor 
INTO @CompanyID, @Date, @SourceId, @DestinationId, @PriceOffice;

END
DROP TABLE #TEMP

CLOSE @RidesForPricingCursor;
DEALLOCATE @RidesForPricingCursor; 

【问题讨论】:

    标签: tsql sql-server-2008-r2 cursor


    【解决方案1】:

    你为什么不只是放下光标(这是一个内存和资源的消耗和主要的性能杀手),只是做一个漂亮的,基于集合的 @ 987654321@:

    UPDATE 
        rfp
    SET
        PriceOffice = rd.PriceOffice
    FROM 
        dbo.vRidesForPricing rfp
    INNER JOIN
        dbo.vRidesDone rd ON rfp.CompanyID = rd.CompanyID
                          AND rfp.SourceId = rd.SourceId
                          AND rfp.DestinationId = rd.DestinationId 
    

    这会更新您期望更新的内容吗?

    【讨论】:

    • 你知道吗..我认为它确实如此:) 谢谢!但是你知道为什么这个光标不起作用吗?为什么“当前的位置”似乎不起作用
    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    相关资源
    最近更新 更多