create or replace procedure update_installdate as
begin
merge into CONTRACTCUSTOMER CC
using (select min(IH.INVOICEDATE) MININVOICEDATE, CC1.CONTRACTCUSTOMER_ID
         from INVOICEHEADER IH, CONTRACTCUSTOMER CC1
        where IH.BILLTOCUSTOMER_LINK_ID = CC1.CUSTOMER_LINK_ID
          and IH.STATUS_ID = 2
          and CC1.INSTALLDATE is null
          and exists
        (select 1
                 from INVOICELINE        IL,
                      INVOICELINEPRODUCT ILP,
                      CONTRACTPRODUCT    CP
                where IL.INVOICEHEADER_ID = IH.INVOICEHEADER_ID
                  and ILP.INVOICELINE_ID = IL.INVOICELINE_ID
                  and ILP.PRODUCT_LINK_ID = CP.PRODUCT_ID
                  and (case
                        when ILP.SIZEDEFINITION_LINK_ID = CP.SIZEDEFINITION_ID then
                         1
                        when CP.SIZEDEFINITION_ID =
                             (select SD.SIZEDEFINITION_ID
                                from SIZEDEFINITION SD
                               where SD.CODE = '*') then
                         2
                        else
                         0
                      end) > 0
                  and ILP.FINISHINGMETHOD_ID = CP.FINISHINGMETHOD_ID
                  and CP.CONTRACT_ID = CC1.CONTRACT_ID
                  )
        group by CC1.CONTRACTCUSTOMER_ID) MERGE_SUBQUERY
on (CC.CONTRACTCUSTOMER_ID = MERGE_SUBQUERY.CONTRACTCUSTOMER_ID)
when matched then
  update
     set CC.INSTALLDATE = MERGE_SUBQUERY.MININVOICEDATE;
     COMMIT;
end update_installdate;
/
execute update_installdate;
drop procedure update_installdate;