通过SQL Cursor

时间:2017-02-22 07:57:22

标签: sql sql-server sql-update cursor

我有两列( TSD_BALANCEUNITS和TSD_UNITSINCERT )。 TSD_BALANCEUNITS 有数值, TSD_UNITSINCERT 有0.00

通过使用光标我想将 TSD_BALANCEUNITS 的值更新为 TSD_UNITSINCERT ,直到从 TSD_BALANCEUNITS 更新为的值总和为止TSD_UNITSINCERT 等于199.00

当移动值的总和等于 199.00 时,

并且正在更新的 TSD_BALANCEUNITS 的值变为0.00并移至 TSD_UNITSINCERT / p>

以下是我正在使用的脚本......

        DECLARE @cnt INT = 0;
        DECLARE @TSD_BALANCEUNITS AS DECIMAL(25, 4)
        DECLARE @TSD_UNITSINCERT AS DECIMAL(25, 4)
        DECLARE @CHECKFLAG AS DECIMAL(25, 4)
        DECLARE LOCK_CERT_UNITS CURSOR LOCAL STATIC
        FOR

        SELECT TSD_BALANCEUNITS
            ,TSD_UNITSINCERT
        FROM IS_TRX_TRX_PROCESSED
        WHERE (TSD_ACCCODE = 8775)
            AND TSD_BALANCEUNITS > 0
        ORDER BY TSD_REALIZEDDATE ASC


        OPEN LOCK_CERT_UNITS

        FETCH NEXT
        FROM LOCK_CERT_UNITS
        INTO @TSD_BALANCEUNITS
            ,@TSD_UNITSINCERT

        WHILE @@FETCH_STATUS = 0 --AND @cnt < 199.00
        BEGIN
            SET @TSD_UNITSINCERT = @TSD_BALANCEUNITS
            SET @CHECKFLAG = + @TSD_BALANCEUNITS

            IF (SUM(@CHECKFLAG) <= 199.00)
            BEGIN
                UPDATE IS_TRX_TRX_PROCESSED
                SET TSD_UNITSINCERT = TSD_BALANCEUNITS
                WHERE (TSD_ACCCODE = 8775)
                    AND TSD_BALANCEUNITS > 0
            END

            PRINT 'BALANCE UNIT =' + CONVERT(VARCHAR(50), @TSD_BALANCEUNITS) + ' ==> ' + 'CERT IN UNITS =' + CONVERT(VARCHAR(50), @TSD_UNITSINCERT);

            FETCH NEXT
            FROM LOCK_CERT_UNITS
            INTO @TSD_BALANCEUNITS
                ,@TSD_UNITSINCERT
        END

        CLOSE LOCK_CERT_UNITS

        DEALLOCATE LOCK_CERT_UNITS
        GO

**TSD_BALANCEUNITS and TSD_UNITSINCERT**

1 个答案:

答案 0 :(得分:0)

此命令:

UPDATE IS_TRX_TRX_PROCESSED
SET    TSD_UNITSINCERT = TSD_BALANCEUNITS
WHERE  (TSD_ACCCODE = 8775)
AND    TSD_BALANCEUNITS > 0

更新所有TSD_ACCCODE = 8775和TSD_BALANCEUNITS&gt;的记录。 0,如果它的总和为999并不重要,你需要以某种方式识别必须更新的记录。

其次,根据结果,这种情况从未发生过。这意味着IF (SUM(@CHECKFLAG) <= 199.00)永远不会成立。我想因为你从未将它的值初始化为0。

SET @CHECKFLAG = 0;