--f_image_update_stockcd(区分, 種別, 汎用C, 汎用サブC, 在庫サイズC, 出品者C, 在庫C, 更新ユーザ, 更新カウンタ)

CREATE OR REPLACE FUNCTION f_image_update_stockcd(
    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 i_stockcd 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,3) THEN
        RAISE EXCEPTION '処理区分が不正です';
    END IF;

    -- 必須チェック
    IF kubun IN (1) THEN
        IF i_imgsizecd IS NULL THEN
            RAISE EXCEPTION '引数 i_imgsizecd は必須です';
        END IF;
    END IF;
    IF kubun IN (1,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) THEN
        IF s_check_length(i_imgsizecd, 1) = FALSE THEN
            RAISE EXCEPTION '引数 imgsizecd が不正です';
        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
            AND sellercd = i_sellercd
            AND stockcd = i_stockcd;

          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, stockcd, updusrnm)
               VALUES(i_typediv, i_generalcd, i_generalsubcd, i_imgsizecd, i_sellercd, i_stockcd, usr);

    -- 削除
    ELSIF kubun = 3 THEN
        DELETE FROM t_image
         WHERE typediv = i_typediv
            AND generalcd = i_generalcd
            AND generalsubcd = i_generalsubcd
            AND imgsizecd = i_imgsizecd
            AND sellercd = i_sellercd
            AND stockcd = i_stockcd;
    END IF;

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

