CREATE OR REPLACE FUNCTION f_image_update(IN kubun integer, IN i_typediv integer, IN i_generalcd integer, IN i_generalsubcd integer, IN i_imgsizecd character varying, IN i_sellercd integer, IN usr character varying, IN count integer, OUT errcd integer, OUT errmsg character varying) AS
$BODY$
DECLARE
    cntcheck integer;
BEGIN
    --
    -- パラメータチェック
    --

    -- 処理区分
    IF kubun IS NULL OR kubun NOT IN (1,2,3) THEN
        RAISE EXCEPTION '処理区分が不正です';
    END IF;

    -- 必須チェック
    IF kubun IN (1,2) THEN
        IF i_imgsizecd IS NULL THEN
            RAISE EXCEPTION '引数 i_imgsizecd は必須です';
        END IF;
    END IF;
    IF kubun IN (1,2,3) THEN
        IF i_typediv IS NULL THEN
            RAISE EXCEPTION '引数 i_typediv は必須です';
        END IF;
        IF i_generalcd IS NULL THEN
            RAISE EXCEPTION '引数 i_generalcd は必須です';
        END IF;
    END IF;

    -- 桁数チェック
    IF kubun IN (1,2) THEN
        IF s_check_length(i_imgsizecd, 1) = FALSE THEN
            RAISE EXCEPTION '引数 name が不正です';
        END IF;
    END IF;

    -- 更新カウンタチェック
    IF kubun IN (2,3) THEN
       SELECT updcnt INTO cntcheck
        FROM t_image
        WHERE typediv = i_typediv
            AND generalcd = i_generalcd
            AND generalsubcd = i_generalsubcd
            AND imgsizecd = i_imgsizecd;
          IF NOT FOUND OR cntcheck <> count THEN
            errcd := -11;
        END IF;
    END IF;

    IF kubun IN (1) THEN
       SELECT updcnt INTO cntcheck
        FROM t_image
        WHERE typediv = i_typediv
            AND generalcd = i_generalcd
            AND generalsubcd = i_generalsubcd
            AND imgsizecd = i_imgsizecd;
          IF NOT FOUND OR cntcheck <> count THEN
            errcd := -11;
          END IF;
    END IF;


    --
    -- 更新処理
    --

    -- 追加
    IF kubun = 1 THEN
        INSERT INTO t_image(typediv, generalcd, generalsubcd, imgsizecd, sellercd, updusrnm, stockcd)
               VALUES    (i_typediv, i_generalcd, i_generalsubcd, i_imgsizecd, i_sellercd, usr, 0);

    -- 更新
    ELSIF kubun = 2 THEN
        UPDATE t_image
           SET imgsizecd = i_imgsizecd,
               sellercd = i_sellercd,
               updusrnm = usr
         WHERE typediv = i_typediv
            AND generalcd = i_generalcd
            AND generalsubcd = i_generalsubcd;

    -- 削除
    ELSIF kubun = 3 THEN
        UPDATE t_image
           SET delflg = TRUE,
               updusrnm = usr
         WHERE typediv = i_typediv
            AND generalcd = i_generalcd
            AND generalsubcd = i_generalsubcd;
    END IF;

    errcd := 1;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
