Código SQL:
Ver originalCREATE TABLE #temp
(
debe INT,
haber INT,
saldo INT
)
CREATE TABLE #resultado
(
debe INT,
haber INT,
saldo INT,
rn INT IDENTITY(1,1)
)
INSERT INTO #temp VALUES (1000,750,350)
INSERT INTO #temp VALUES (5000,6500,NULL)
INSERT INTO #temp VALUES (760 ,1000,NULL)
INSERT INTO #temp VALUES (10560 ,5000,NULL)
INSERT INTO #temp VALUES (2300 ,1560,NULL)
SELECT *, IDENTITY(INT,1,1) AS rn INTO #temp2 FROM #temp
DECLARE @x INT
DECLARE @saldo INT
DECLARE @suma INT
SET @x=1
SET @saldo=0
while (@x<=(SELECT COUNT(*) FROM #temp2))
BEGIN
IF @x=1
BEGIN
SELECT @saldo=saldo FROM #temp2 WHERE rn=@x
INSERT INTO #resultado
SELECT debe,haber, @saldo AS saldo FROM #temp2 WHERE rn=@x
END
ELSE
BEGIN
INSERT INTO #resultado
SELECT debe,haber,debe-haber + @saldo AS saldo FROM #temp2 WHERE rn=@x
SELECT @saldo=saldo FROM #resultado WHERE rn=@x
END
SET @x=@x+1
END
SELECT * FROM #resultado
saludos!