--删除某单据重复的出入库流水
if not object_id('tempdb..#min') is null
drop table #min
select voucher_no, item_no, branch_no, db_no, real_qty, sheet_amt, min_no = min(sheet_no)
into #min
from wh_inout_flow a
where voucher_no = '修改为单号'
group by voucher_no, item_no, branch_no, db_no, real_qty, sheet_amt
having count(1) > 1
update x set stock_qty = x.stock_qty - b.qty
from wh_stock x
inner join (
select f.item_no, f.branch_no, qty = sum(case when f.db_no = '+' then f.real_qty else -f.real_qty end)
from wh_inout_flow f
inner join #min b on b.voucher_no=f.voucher_no and b.item_no=f.item_no and b.branch_no=f.branch_no and b.db_no=f.db_no and b.real_qty=f.real_qty and b.sheet_amt=f.sheet_amt
where f.sheet_no <> b.min_no
group by f.item_no, f.branch_no) b on b.item_no = x.item_no and b.branch_no = x.branch_no
delete x
from wh_inout_flow x
inner join #min b on b.voucher_no=x.voucher_no and b.item_no=x.item_no and b.branch_no=x.branch_no and b.db_no=x.db_no and b.real_qty=x.real_qty and b.sheet_amt=x.sheet_amt
where x.sheet_no <> b.min_no
drop table #min