/** 更新 财务应收单.账龄起算日 add by bjkai_wang */
IF EXISTS(SELECT 1 FROM T_AR_FinArBill_E WHERE FAcctAgeCalcDate is null)
update T_AR_FinArBill_E t1 set FAcctAgeCalcDate = (
  select FAcctAgeCalcDate 
  from (
    select ext.FID,
    case 
      when fin.FSourceBillType = 'ar_busbill' then
        bus.FBizDate
      when fin.FSourceBillType = 'ar_invoice' then
        case when inv.FSourceBillType = 'ar_busbill' then
          bus2.FBizDate
        else
          fin.FBizDate
        end
      else
        fin.FBizDate
    end as FAcctAgeCalcDate
    from T_AR_FinArBill_E ext 
    inner join T_AR_FinArBill fin on fin.FID = ext.FID
    left join T_AR_BusBill bus on to_char(bus.FID) = fin.FSourceBillID 
    left join T_AR_Invoice inv on to_char(inv.FID) = fin.FSourceBillID 
    left join T_AR_BusBill bus2 on to_char(bus2.FID) = inv.FSourceBillID 
  ) t2 where t2.FID = t1.FID
);