Delimiter //
/**
    In batchnum Int : num du lot
*/

Drop Procedure if exists LOADER_REFDATA_DELETE_OLD_ACCOUNTSREFS//

Create Procedure LOADER_REFDATA_DELETE_OLD_ACCOUNTSREFS (
    In batchnum int
    , In idEntities int
)
Begin
	deleteOld: Begin
        Delete ARD
        From 
			LOADER_STATUS LST
			Inner Join LOADER_REFDATA LARD	
				On LARD.LOADER_STATUS_ID_LOADER_STATUS = LST.ID_LOADER_STATUS
			Inner Join ENTITIES_REF_TYPES ERT
				On LARD.LOADER_REFDATA_TYPE = ERT.ENTITIES_REF_TYPES_CODE
			Inner Join ACC_REF_DATAS ARD
				On ARD.ACCOUNTS_ID_ACCOUNTS = LARD.ACCOUNTS_ID_ACCOUNTS
            Inner Join ENTITIES_REF_DATAS ERD
                On ARD.ENT_REF_DATAS_ID_ENT_REF_DATAS = ERD.ID_ENTITIES_REF_DATAS
            Inner Join ENTITIES_REF ETR
                On ERD.ENTITIES_REF_ID_ENTITIES_REF = ETR.ID_ENTITIES_REF
                And ETR.ENTITIES_REF_SEQUENCE = LARD.ENTITIES_REF_SEQUENCE
                And ETR.ENT_REF_TYPE_ID_ENT_REF_TYPES = ERT.ID_ENTITIES_REF_TYPES
        Where 
            LST.LOADER_STATUS_ERRCOUNT = 0  
            And LST.LOADER_STATUS_BATCH_NUM = batchnum
			And ETR.ENTITIES_ID_ENTITIES = idEntities
			And LARD.LOADER_REFDATA_TYPE Like '%ACCOUNTS'
        ;

    end ;
End //

Delimiter ;