很多新的Sql循环&游标迫切需要推动。请指导我。
With tbl as (
select empcode, refid
from tbltrans where date < getdate()
group by empcode, refid
)
select r.empcode, r.refid, sum(t.debit)debit, sum(t.credit)credit,
(sum(t.credit)- sum(t.debit))balance
from ref r
left join tbltrans t on r.empcode = t.empcode and r.refid = t.refid
group by r.empcode, r.refid
以上查询结果如下:
empcode refid debit credit balance
----------------------------------------------
e1 r1 0 5 5
e1 r2 2 6 4
e2 r3 3 2 -1
现在,我必须插入带有相关借方值的新记录,以使余额为0,即
empcode refid debit credit
-----------------------------------
e1 r1 5 0
e1 r2 4 0
e2 r3 -1 0
我该怎么办?这就是我能想到的。
DECLARE @empcode nvarchar(11) , @refid nvarchar(11)
DECLARE c1 CURSOR READ_ONLY
FOR
//The above t-sql query here
OPEN c1
FETCH NEXT FROM c1 INTO @empcode
WHILE @@FETCH_STATUS = 0
BEGIN
Insert into tbltransactions values(@empcode, @refid, @somevaluefordebit, 0)
FETCH NEXT FROM c1 INTO @empcode
END CLOSE c1
DEALLOCATE c1
答案 0 :(得分:5)
不需要游标或循环:
INSERT INTO tbltransactions(empcode, refid, debit, credit)
SELECT empcode,
refid,
balance,
0
FROM tbltransactions