将一个变量分配给其他变量(SQL)

时间:2012-09-25 09:23:39

标签: sql tsql variables

我正在用一些计算方法编写一小段代码,并使用temp varibles来执行它。

当我只是将SELECT语句分配给@sum1时,它正在运行,但当我将其更改为@sum1 += SELECT...时,它会返回NULL(参见附图)

我已经尝试过以下内容:

  • 试图做一些演员(尽管@ sum1和activityDur都被定义为INT)

  • 尝试将SELECT个参数分配到一个变量中,然后将该变量分配给一个新变量。

  • 试图通过网络找到类似的问题(包括stackoverflow)

THX。

SET @sum1=0
        WHILE @i <= 10
            BEGIN   
 //**** HERE IS THE PROBLEM
SET @sum1 += (SELECT activityDur FROM dbo.tmp_activityCalculation WHERE RowNum = @i)
//**** 
IF (@sum1 > 200)
                    BEGIN
                        SET @index += 1
                        SET @sum1 = 0
                    END
                INSERT INTO tmp_finalCalc (RowNum, activityID, activityDur,actDay)
                SELECT 
                    RowNum,
                    activityID,
                    activityDur,
                    @sum1
                FROM tmp_activityCalculation WHERE Rownum = @i      
                SET @i += 1
            END

Execution Result of the Query

1 个答案:

答案 0 :(得分:1)

SET @sum=0
    WHILE @i <= 10!
            BEGIN   
     //**** HERE IS THE PROBLEM
            SELECT @sum1=isnull(@sum1,0)+isnull(activityDur,'0') FROM dbo.tmp_activityCalculation WHERE RowNum = @i
    //**** 
                IF (@sum1 > 200)
                    BEGIN
                        SET @index += 1
                        SET @sum1 = 0
                    END
                INSERT INTO tmp_finalCalc (RowNum, activityID, activityDur,actDay)
                SELECT 
                    RowNum,
                    activityID,
                    activityDur,
                    @sum1
                FROM tmp_activityCalculation WHERE Rownum = @i      
                SET @i += 1
            END