Thanks to all for your comments! To implement penny rounding, you simply need to change the zero (second argument of ROUND) of the "a" CTE to 2:
a AS (
SELECT d.key1, d.key2, d.Weight, d.SeqNo
,ROUND(CAST(Amount * d.Weight / w.Weight AS Money), 0) As AllocAmt
INNER JOIN @hdr h ON h.key1 = d.key1
INNER JOIN w ON h.key1 = w.key1)
As Tom-John and Janus have noted, there are other approaches. A couple of key thoughts to keep in mind:
1. Mostly this will be used where the amounts being allocated are typically in the 1000s or 100,000s of dollars. If this allocation is performed over 100 rows, the maximum "leftover" will be 99, so the "fudged" amount represents generally less than 1% of the amount alllocated.
2. Because roughly 50% of the rows will round down and 50% will round up, in practice there will rarely be (except in contrived cases) where the leftover amount is significant.
I'm not saying this is the only way to fudge round, only that it worked for us in practice.
As to fraud, I can honestly say that I've never passed an accounting course so I'm no expert. All I know is that our accountants seemed to accept it. 🙂
My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]
My thought question: Have you ever been told that your query runs too fast?
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]