Delimiter //
/**
    In batchnum Int : num du lot
*/
Drop Procedure if exists LOADER_LINKEDACCOUNTS_DELETE//
Create Procedure LOADER_LINKEDACCOUNTS_DELETE (
    In batchnum int
)
Begin
		-- supression si compte de consolidation et compte consolidé fournis
        Delete
            trgt
        From
            ACCOUNTS_has_ACCOUNTS trgt
            Inner Join LOADER_LINKEDACCOUNTS src
                On trgt.ACCOUNTS_ID_ACCOUNTS = src.ACCOUNTS_ID_ACCOUNTS
				And trgt.ACCOUNTS_ID_ACCOUNTS_LINK = src.ACCOUNTS_ID_ACCOUNTS_LINKED
			Inner Join LOADER_STATUS LST
				On src.LOADER_STATUS_ID_LOADER_STATUS = LST.ID_LOADER_STATUS
		Where
			LST.LOADER_STATUS_BATCH_NUM = batchnum
			And LST.LOADER_STATUS_ERRCOUNT = 0
			And src.LOADER_LINKEDACCOUNTS_REMOVE <> 0 
			And src.ACCOUNTS_ID_ACCOUNTS is Not null
			And src.ACCOUNTS_ID_ACCOUNTS_LINKED is Not null
        ;
		-- supression si compte de consolidation fournis, compte consolidé non fournis
        Delete
            trgt
        From
            ACCOUNTS_has_ACCOUNTS trgt
            Inner Join LOADER_LINKEDACCOUNTS src
                On trgt.ACCOUNTS_ID_ACCOUNTS = src.ACCOUNTS_ID_ACCOUNTS
			Inner Join LOADER_STATUS LST
				On src.LOADER_STATUS_ID_LOADER_STATUS = LST.ID_LOADER_STATUS
		Where
			LST.LOADER_STATUS_BATCH_NUM = batchnum
			And LST.LOADER_STATUS_ERRCOUNT = 0
			And src.LOADER_LINKEDACCOUNTS_REMOVE <> 0 
			And src.ACCOUNTS_ID_ACCOUNTS is Not null
			And src.ACCOUNTS_ID_ACCOUNTS_LINKED is null
        ;
		-- supression si compte de consolidation non founis et compte consolidé fournis
        Delete
            trgt
        From
            ACCOUNTS_has_ACCOUNTS trgt
            Inner Join LOADER_LINKEDACCOUNTS src
                On trgt.ACCOUNTS_ID_ACCOUNTS_LINK = src.ACCOUNTS_ID_ACCOUNTS_LINKED
			Inner Join LOADER_STATUS LST
				On src.LOADER_STATUS_ID_LOADER_STATUS = LST.ID_LOADER_STATUS
		Where
			LST.LOADER_STATUS_BATCH_NUM = batchnum
			And LST.LOADER_STATUS_ERRCOUNT = 0
			And src.LOADER_LINKEDACCOUNTS_REMOVE <> 0 
			And src.ACCOUNTS_ID_ACCOUNTS is null
			And src.ACCOUNTS_ID_ACCOUNTS_LINKED is Not null
        ;

End //

Delimiter ;


