0

In the following while loop, the variable @total is resulted as NULL when adding selected value from table. If not adding, the result is shown as selected value from table but only the last row's value.

SET @coundDate = '1/1/2012';

WHILE ( Datepart(dd, @countDate) < Datepart(dd, @endDate) )
  BEGIN
      SET @total = @total + (SELECT Cast([7am] AS INT) + 
                                    Cast([8am]AS INT) AS TotalHitCount
                             FROM   Sale
                             WHERE  TransactionDate = @countDate);
      SET @countDate = Dateadd(d, 1, @countDate);
  END;

SELECT @total 

I'm now confusing a lot. What's that error?

3
  • 1
    Why are you doing this in a loop. Won't SUM work for you? Commented Oct 29, 2012 at 8:19
  • How to 'group by' in this condition? Commented Oct 29, 2012 at 8:24
  • From the code you have shown you wouldn't need a group by. Just a where to select only the rows of interest. Commented Oct 29, 2012 at 8:25

2 Answers 2

1

As Martin points out, you could write your entire query as a simple SUM:

SELECT SUM(Cast([7am] AS INT) + Cast([8am]AS INT)) AS Total
FROM   Sale
WHERE  TransactionDate between '20120101' and @endDate

Although I would query why 7am and 8am aren't already ints.

Sign up to request clarification or add additional context in comments.

1 Comment

Probably safer to do SUM(ISNULL(Cast([7am] AS INT),0) + ISNULL(Cast([8am] AS INT),0)) AS Total. One of the reasons they might have got their original behaviour would be if one of the values is NULL and this will lose the non null value.
1

You have to pre-init your variable with default value like 0 :)

4 Comments

@NayLinAung - you're not initializing @total in the code you've shown (although the code you've shown obviously isn't your real code)
@Damien_The_Unbeliever - If you can't help, please don't make useless assumptions. It is the real code in my Business Activity Monitoring System of BIT project. How can I show every pieces of the code? I only posted the part of code where error occurred.
Useless assumptions? Your first line assigns to a variable called @coundDate, not @countDate. Therefore, this isn't the real code. All we can work with is what you do post.
@Damien_The_Unbeliever - that's my only typing error. Sorry for that. And I think it is not too much related with the error. If my comment insulted u, I'm really sorry for that. I swear that's my real code and I am here to find out the answer, not to argue about non-related factors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.