我在sql server 2005中创建一个udf返回一个表,我在udf中使用这个表来计算客户端的solde,但有时候结果是正确的,有时是不正确的(错误值在字段中“Solde” “)表达式@ Solde = @Solde + @Debit - @Credit
这是函数的代码:
CREATE FUNCTION HistoryClient
(
@IdClient int
)
RETURNS @Table_Var
TABLE ( NAuto BigInt Identity(1,1),
Numero nvarchar(20),
Ligne nvarchar(50),
IdClient int,
Matricule nvarchar(30),
DateBL datetime,
Libelle nvarchar(50),
Qte decimal(18, 2),
PU money,
Debit money,
Credit money,
Solde money
)
AS
BEGIN
Declare @SoldeInitial money
DECLARE @Debit money
DECLARE @Credit money
DECLARE @Solde money
DECLARE @Solde1 money
DECLARE @Ligne nvarchar(50)
DECLARE History_Cursor CURSOR FOR
SELECT Ligne, Debit, Credit, Solde
FROM @Table_Var
FOR UPDATE OF Solde
Select @SoldeInitial = SoldeInitial
From Client
Where IdClient= @IdClient
INSERT INTO @table_Var (Numero, Ligne, IdClient, Matricule, DateBL, Libelle, Qte, PU, Debit, Credit, Solde)
Select Numero, Ligne, IdClient, Matricule, DateBL, Libelle, Qte, PU, Debit, Credit, 0
From vwHistoryAllClients
Where IdClient= @IdClient
Order By Ligne
OPEN History_Cursor
FETCH NEXT FROM History_Cursor Into @Ligne, @Debit, @Credit, @Solde1
SET @Solde = @SoldeInitial
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Solde= @Solde + @Debit - @Credit
UPDATE @Table_Var
SET Solde = @Solde
WHERE CURRENT Of History_Cursor
FETCH NEXT FROM History_Cursor Into @Ligne, @Debit, @Credit, @Solde1
END
CLOSE History_Cursor
DEALLOCATE History_Cursor
RETURN
END
任何解决方案
答案 0 :(得分:0)
SELECT
定义中的CURSOR
语句没有ORDER BY
子句。这意味着无法保证从游标返回行的顺序。
从我收集的内容中,您正在尝试计算Solde列中的运行总和。但是,由于ORDER BY Ligne
定义中没有CURSOR
,因此无法保证Solde
将成为Ligne
订单后的运行总和。也许这会让你得出结论,有时结果是正确的,有时它不是。
但是,在ORDER BY
声明中添加CURSOR
子句会使其成为READ ONLY
。请参阅following Stackoverflow thread了解原因。
如果实际上您需要在Solde列中计算(Credit-Debit)的运行总和,请参阅following Stackoverflow thread计算SQL Server中的运行总和。