账单表,字段ID,账单号,账单金额 币种 核销金额 余额 是否全部核销
如下:
ID BILL_NO BILL_NUM MONEY_TYPE CONFIRM_NUM_TOTAL BALANCE IS_CONFIRM
1 B0001 500 USD 0 500 N
2 B0002 100 USD 0 100 N
3 B0003 300 RUB 0 300 N
费用表,字段ID ,账单号,金额,币种,核销金额 余额 是否全部核销
ID BILL_NO AMOUNT MONEY_TYPE CONFIRM_NUM_TOTAL BALANCE IS_CONFIRM
1 B0001 200 USD 0 200 N
2 B0001 300 USD 0 300 N
3 B0002 100 USD 0 100 N
4 B0003 100 RUB 0 100 N
5 B0003 200 RUB 0 300 N
核销过程是 列出费用表,核销的时候可以多个账单同时核销,
比如 :勾选费用ID1,3 核销账单B0001(部分费用),B0002(全部费用)
求一个事务sql, 传入参数怎么设置比较合理?
------解决思路----------------------
我只能猜一下你的意思。
create table t1(
id int identity(1,1)
,bill_no varchar(100)
,balance int
)
create table t2(
id int identity(1,1)
,bill_no varchar(100)
,amount int
)
insert into T1 (bill_no,balance) values
('b0001',500)
,('b0002',100)
,('b0003',300)
insert into T2 (bill_no,amount) values
('b0001',200)
,('b0001',300)
,('b0002',100)
,('b0003',100)
,('b0003',200)
select * from T1;
select * from T2;
update a set a.balance-=b.amount from T1 a join (select bill_no,SUM(amount) as amount from T2 where ID in(1,3) group by bill_no) b on a.bill_no=b.bill_no
select * from T1;
/*
id bill_no balance
----------- ------------ -----------
1 b0001 300
2 b0002 0
3 b0003 300
*/
------解决思路----------------------
DECLARE @费用IDS VARCHAR(8000)
SET @费用IDS='1,3'
BEGIN TRAN
SET @费用IDS=','+@费用IDS+','
UPDATE T1
SET CONFIRM_NUM_TOTAL=CONFIRM_NUM_TOTAL+T2.BALANCE
,BALANCE=T1.BALANCE-T2.BALANCE
,IS_CONFIRM=CASE WHEN T1.BALANCE>T2.BALANCE THEN'N'ELSE'Y'END
FROM 账单表 T1
JOIN(
SELECT BILL_NO,SUM(BALANCE)BALANCE FROM 费用表
WHERE @费用IDS LIKE '%,'+CAST(ID AS VARCHAR(10))+',%'
GROUP BY BILL_NO
) T2 ON T1.BILL_NO=T2.BILL_NO
UPDATE 费用表
SET CONFIRM_NUM_TOTAL=BALANCE
,BALANCE=0
,IS_CONFIRM='Y'
WHERE @费用IDS LIKE '%,'+CAST(ID AS VARCHAR(10))+',%'
COMMIT TRAN;