Should this be happening?

  • Something I've just picked up on - I know why this is happening, but whether it should remains a mystery to me.  Does anyone know about this, is it documented and should it be happening?  Or have I just fundamentally misunderstood something?

    Run this:

    use Northwind

    declare @f decimal(7,2)

    select @f = 0

    select @f = @f + Freight from Orders

    select @f

    select sum(Freight) from Orders

    You'll get this result set:

             

    ---------

    64942.69

    (1 row(s) affected)

                         

    ---------------------

    64942.6900

    (1 row(s) affected)

    Surely you should get this:

             

    ---------

    8.53

    (1 row(s) affected)

                         

    ---------------------

    64942.6900

    (1 row(s) affected)

    Which is actually the result set from:

    use Northwind

    declare @f decimal(7,2)

    select @f = 0

    select @f = Freight from Orders

    select @f

    select sum(Freight) from Orders

    It seems to be adding Freight to @f on each row it scans through, hence coming up with the sum.  It does raise the question of performance comparisons but won't get the time for this for a little while yet.

  • Makes sense to me....

    You are basically setting the @f to the value of Freight which is basically a sum of the rows.



    Shamless self promotion - read my blog http://sirsql.net

  • You are correct that it should not happen.  Any such operation should be set-based and not expose any internal "cursor" behavior like this.  It's a well-known "feature" of SQL Server, and comes in handly for some denormalizing shortcuts, e.g. my example on this thread:

    http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=8&messageid=105513

     



    --Jonathan

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply