Gil Peretz
Gil Peretz

Reputation: 2419

Assign one variable to other variable (SQL)

I'm writing a short piece of code with some calculation method, and im using temp varibles in order to perform it.

When I'm just assigning the SELECT statment to @sum1 it's working, but when I'm changing it to @sum1 += SELECT... it return NULL (see picture attached)

I've already tried the following:

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

Upvotes: 1

Views: 3732

Answers (1)

AnandPhadke
AnandPhadke

Reputation: 13496

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

Upvotes: 1

Related Questions