Reputation: 938
I'm building a function to return the net value of a sales invoice once any purchase invoices marked against it have been taken off - part of these costs are contractor costs of which we also want to calculate either NI or a set increase to the contractor pay to reflect "true" value.
So on one sales invoice, we may have several contractors where we have purchase invoices against it, some may be at NI calculated at 13.8%, others may be at a standard "uplift" of 10% and others may be at 0% added.
The bit that I'm trying to figure out is if I need to make the whole function as a cursor as there are going to be different figures for a variable for each purchase invoice e.g.
(SELECT SUM(th.hoursworked * (th.payrate * (1 + (@NIAMOUNT / 100))) )
but the @NIAMOUNT will have to change for each purchase invoice.
Is the best way of doing this via a cursor, or is there a better way of doing this?
Sorry if this is a bit verbose!
Upvotes: 2
Views: 157
Reputation: 107247
You should avoid cursors wherever possible - cursors operate 'serially' which will limit SQL's performance.
If the calculation is simple, one way to do this would be do do the NI lookup inline, e.g.
(SELECT SUM(th.hoursworked * (th.payrate * (1 +
((CASE somejoinedtable.UpliftType
WHEN 1 THEN 10
WHEN 2 THEN 13.8
WHEN 3 THEN 0
END
/ 100))))
If this becomes too messy to do inline, you could abstract a user defined function
CREATE FUNCTION dbo.fnGetNIAmount(int @someLookupParam)
...
And then do like so
(SELECT SUM(th.hoursworked * (th.payrate * (1 +
((dbo.fnGetNIAmount(somejoinedtable.UpliftType )
/ 100))))
Upvotes: 2
Reputation: 51494
You almost certainly don't need a cursor
Join your hours worked to the contract they are based on, and take the NI value from the contract.
Upvotes: 2