Delimiter //
/**
 * Author:  armen
 * Created: 9 mars 2018
 */
Drop Procedure if exists LOADER_EDMINDEX_METADATA_INSERT //
Create Procedure LOADER_EDMINDEX_METADATA_INSERT (
    In batchnum int
    , In lastId Int
)
Begin
    Set @lemdi_lastId = lastId;
    Set @lemdi_batchnum = batchnum;
	Insert Into DOCUMENTS_METADATA (
        DOCUMENTS_ID_DOCUMENTS
        , DOCUMENTS_METADATA_KEY, DOCUMENTS_METADATA_INT
        , DOCUMENTS_METADATA_EXTID, DOCUMENTS_METADATA_DATE
        , DOCUMENTS_METADATA_DECIMAL, DOCUMENTS_METADATA_REF
        , DOCUMENTS_METADATA_CONTENT
    )
    Select 
        Coalesce(tbl1.ID_DOCUMENTS_NEW + @lemdi_lastId, tbl1.ID_DOCUMENTS) DOCUMENTS_ID_DOCUMENTS
        , src.DOCUMENTS_METADATA_KEY, src.DOCUMENTS_METADATA_INT
        , src.DOCUMENTS_METADATA_EXTID, src.DOCUMENTS_METADATA_DATE
        , src.DOCUMENTS_METADATA_DECIMAL, src.DOCUMENTS_METADATA_REF
        , src.DOCUMENTS_METADATA_CONTENT
    From
        LOADER_STATUS sts
        Inner Join LOADER_EDMINDEX tbl1
            On sts.ID_LOADER_STATUS = tbl1.LOADER_STATUS_ID_LOADER_STATUS
        Inner Join LOADER_EDMINDEX_DOCUMENTS_METADATA src
            On tbl1.ID_LOADER_EDMINDEX = src.LOADER_EDMINDEX_ID_LOADER_EDMINDEX
        Left Join DOCUMENTS_METADATA tar
            On tbl1.ID_DOCUMENTS = tar.DOCUMENTS_ID_DOCUMENTS
            And src.DOCUMENTS_METADATA_KEY = tar.DOCUMENTS_METADATA_KEY
    Where
        sts.LOADER_STATUS_ERRCOUNT = 0
        And tar.ID_DOCUMENTS_METADATA is null
        And Trim(Coalesce(src.DOCUMENTS_METADATA_KEY, '')) <> ''
        And sts.LOADER_STATUS_BATCH_NUM = @lemdi_batchnum
    ;
End //

Delimiter ;
