simon
2012-02-28 09:47:12 UTC
I can get total of sales by month by using update to local variable.
Example:
DECLARE @totalTbl TABLE (monthID tinyInt, sales int, salesSum int)
DECLARE @RunningSum int
SET @RunningSum= 0
INSERT INTO @totalTbl
SELECT monthID, sales, null
FROM orders
ORDER BY monthID
UPDATE @totalTbl
SET @RunningSum = salesSum = @RunningSum + sales
FROM @totalTbl
SELECT * FROM @totalTbl
It works. But the problem is that UPDATE statement doesn't guarantee
the order of update. I can't say:
UPDATE @totalTbl SET @RunningSum = salesSum = @RunningSum + sales
FROM @totalTbl
ORDER BY monthID
Is there some difference if I put clustered index on table variable:
DECLARE @totalTbl TABLE (monthID tinyInt primary key, sales int,
salesSum int)
I guess than this way update will be always ordered by monthID, but I
need some confirmation :)
br,
Simon
Example:
DECLARE @totalTbl TABLE (monthID tinyInt, sales int, salesSum int)
DECLARE @RunningSum int
SET @RunningSum= 0
INSERT INTO @totalTbl
SELECT monthID, sales, null
FROM orders
ORDER BY monthID
UPDATE @totalTbl
SET @RunningSum = salesSum = @RunningSum + sales
FROM @totalTbl
SELECT * FROM @totalTbl
It works. But the problem is that UPDATE statement doesn't guarantee
the order of update. I can't say:
UPDATE @totalTbl SET @RunningSum = salesSum = @RunningSum + sales
FROM @totalTbl
ORDER BY monthID
Is there some difference if I put clustered index on table variable:
DECLARE @totalTbl TABLE (monthID tinyInt primary key, sales int,
salesSum int)
I guess than this way update will be always ordered by monthID, but I
need some confirmation :)
br,
Simon