2

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!

4

2 回答 2

2

你几乎肯定不需要光标

将您的工作时间加入他们所基于的合同中,并从合同中获取 NI 值。

于 2012-08-29T09:54:47.747 回答
2

您应该尽可能避免使用游标——游标“串行”操作,这将限制 SQL 的性能。

如果计算很简单,一种方法是做 NI 查找内联,例如

(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)))) 

如果这变得太混乱而无法内联,您可以抽象一个用户定义的函数

CREATE FUNCTION dbo.fnGetNIAmount(int @someLookupParam)
...

然后像这样

(SELECT SUM(th.hoursworked * (th.payrate * (1 + 
                                           ((dbo.fnGetNIAmount(somejoinedtable.UpliftType )
                                        / 100)))) 
于 2012-08-29T09:56:42.777 回答