迭代SQL Server表并插入行

时间:2015-06-25 19:57:14

标签: sql-server iteration

表格(表1)的数据如下:

+-----------+-----------+-----------+---------+
| AccountNo | OldBranch | NewBranch | Balance |
+-----------+-----------+-----------+---------+
|    785321 |        10 |        20 |    -200 |
|    785322 |        10 |        20 |     300 |
+-----------+-----------+-----------+---------+

使用逻辑:
如果余额为负(即<0)则必须借记NewBranch(Dr)并且必须记入Old Branch(Cr);
如果余额为正数(即> 0)则必须借记OldBranch(Dr)并且必须记入New Branch(Cr);
如下所示的行必须插入另一个表(表2)

+------------+------+--------+--------+
| Account NO | DrCr | Branch | Amount |
+------------+------+--------+--------+
|     785321 | Dr   |     20 |    200 |
|     785321 | Cr   |     10 |    200 |
|     785322 | Cr   |     20 |    300 |
|     785322 | Dr   |     10 |    300 |
+------------+------+--------+--------+

使用Cursor有什么可能的解决方案?

谢谢,

3 个答案:

答案 0 :(得分:0)

你没有提供太多详细信息,但这样的事情应该非常接近。

update nb
set Balance = Balance - ABS(t1.Balance)
from NewBranch nb
join Table1 t1 on t1.AccountNo = nb.AccountNo
where nb.Balance < 0

update ob
set Balance = Balance - ABS(t1.Balance)
from OldBranch ob
join Table1 t1 on t1.AccountNo = ob.AccountNo
where ob.Balance > 0

答案 1 :(得分:0)

你绝对不需要游标,只需要一组插入语句

INSERT INTO Table2 (AccountNo,DrCr,Branch,Amount) 
SELECT AccountNo,'Dr',IIF(Balance<0,NewBranch,OldBranch),IIF(balance<0,-1*balance,balance) FROM Table1
UNION ALL
SELECT AccountNo,'Cr',IIF(Balance>0,NewBranch,OldBranch),IIF(balance<0,-1*balance,balance) FROM Table1

答案 2 :(得分:0)

declare @t table (Accountno int,
                  OldBranch INT,
                  NewBranch int,
                  Balance int)
insert into @t (Accountno,
               OldBranch,
               NewBranch,
               Balance)
values (785321,10,20,200),
       (785322,10,20,300)

select Accountno,Y.CRDR,Y.Branch,Y.Amount from @t CROSS APPLY 
(Select 'Dr' AS CRDR,OldBranch AS Branch,Balance As Amount 
       UNION ALL 

   Select 'Cr',NewBranch,Balance)y