Delimiter //
/**
 * Author:  armen
 * Created: 19 mai 2022
 */

Drop Procedure If Exists BUSINESS_TEMPLATE_LOADER_CP_SCHEME //
Create Procedure BUSINESS_TEMPLATE_LOADER_CP_SCHEME(
    In srcTemplaterLoaderId int
, In tarTemplaterLoaderId int
, In templaterLoaderType varchar(50)
)
Begin
    Main: Begin

        Set @sourceToCopy = Coalesce(
                (
                    Select
                        TEMPLATE_IMPORT_SCHEME_XML
                    From
                        TEMPLATE_IMPORT_SCHEME
                    Where
                            `TEMPLATE_LOADER_ID_TEMPLATE_LOADER` = srcTemplaterLoaderId
                      And `TEMPLATE_IMPORT_SCHEME_NAME` = templaterLoaderType
                )
            , ''
            );

        Set @indexTar = Coalesce(
                (
                    Select
                        ID_TEMPLATE_IMPORT_SCHEME
                    From
                        TEMPLATE_IMPORT_SCHEME
                    Where
                            `TEMPLATE_LOADER_ID_TEMPLATE_LOADER` = tarTemplaterLoaderId
                      And `TEMPLATE_IMPORT_SCHEME_NAME` = templaterLoaderType
                )
            , 0
            );

        If @indexTar > 0 Then

Update TEMPLATE_IMPORT_SCHEME
Set TEMPLATE_IMPORT_SCHEME_XML = @sourceToCopy
WHERE ID_TEMPLATE_IMPORT_SCHEME = @indexTar;
Else

            Insert Into TEMPLATE_IMPORT_SCHEME (
                TEMPLATE_LOADER_ID_TEMPLATE_LOADER, TEMPLATE_IMPORT_SCHEME_NAME, TEMPLATE_IMPORT_SCHEME_XML
            ) VALUES (tarTemplaterLoaderId, templaterLoaderType, @sourceToCopy);
End If;
End;
End //

Delimiter ;