-- A5M2で実行時に[SQL] - [スラッシュ(/)のみの行でSQLを区切る]に変えてから実行する
CREATE PROCEDURE src05.inst_merge_laundering(target_table VARCHAR(255))
SQL SECURITY INVOKER
BEGIN
    -- スキーマ名
    DECLARE schema_name VARCHAR(50) DEFAULT (SELECT DATABASE());
    -- プロシージャ名
    DECLARE procedure_name VARCHAR(100) DEFAULT 'inst_merge_laundering';
    -- プロシージャの引数
    DECLARE procedure_args JSON DEFAULT JSON_OBJECT('target_table', target_table);

    -- 例外処理
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
        BEGIN
            GET DIAGNOSTICS CONDITION 1
                @error_state = RETURNED_SQLSTATE, @error_msg = MESSAGE_TEXT;
            CALL medaca_common.put_error_log(schema_name, procedure_name, procedure_args,
                                    'inst_merge_launderingでエラーが発生', @error_state, @error_msg);
            SET @error_msg = (
                CASE
                WHEN LENGTH(@error_msg) > 128 THEN CONCAT(SUBSTRING(@error_msg, 1, 125), '...')
                ELSE @error_msg
                END
            );
            SIGNAL SQLSTATE '45000'
                SET MYSQL_ERRNO = @error_state, MESSAGE_TEXT = @error_msg;
        END;

    SET @error_state = NULL, @error_msg = NULL;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '【洗替】４：メルク施設コードの洗替_B① 開始');

    SET @update_institution = "
        UPDATE (
                SELECT
                    dcf_dsf_inst_cd,
                    dup_opp_cd,
                    form_inst_name_kanji,
                    form_inst_name_kana,
                    inst_addr,
                    prefc_cd
                FROM
                    internal05.inst_merge_t
            ) AS imt,
            $$target_table$$ AS tt
        SET 
            tt.inst_cd = imt.dup_opp_cd,
            tt.inst_name = imt.form_inst_name_kanji,
            tt.inst_name_kana = imt.form_inst_name_kana,
            tt.address = imt.inst_addr,
            tt.pref_cd = imt.prefc_cd,
            tt.dwh_upd_dt = SYSDATE()
        WHERE
                tt.inst_cd = imt.dcf_dsf_inst_cd
            AND tt.inst_clas_cd = '1'
    ";
    SET @update_institution = REPLACE(@update_institution, "$$target_table$$", target_table);
    PREPARE update_institution_stmt from @update_institution;
    EXECUTE update_institution_stmt;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '【洗替】４：メルク施設コードの洗替_B① 終了');

END