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

Drop Procedure if exists LOADER_REFDATALABEL_REF_DATA_INSERT//

Create Procedure LOADER_REFDATALABEL_REF_DATA_INSERT (
    In batchnum int
    , In lastidRefData int
)
Begin
	Set @lastidRefData = lastidRefData;
    Insert Into ENTITIES_REF_DATAS (
        ID_ENTITIES_REF_DATAS
        , ENTITIES_REF_ID_ENTITIES_REF
        , ENTITIES_REF_DATAS_CODE
    )
    Select Distinct
            ARD.NEW_ID_ENTITIES_REF_DATAS + @lastidRefData
            , ARD.ENTITIES_REF_ID_ENTITIES_REF
            , ARD.ENTITIES_REF_DATA_CODE
    From LOADER_STATUS S 
		Inner Join LOADER_REFDATALABEL ARD
            On ARD.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
    Where 
        S.LOADER_STATUS_ERRCOUNT = 0
        And ARD.ID_ENTITIES_REF_DATAS Is Null
        And ARD.NEW_ID_ENTITIES_REF_DATAS Is Not Null
        AND S.LOADER_STATUS_BATCH_NUM = batchnum

    ;
End //

Delimiter ;
