CREATE OR REPLACE FUNCTION f_image_import (IN i_makeritemcd character varying, IN i_typediv integer, IN i_imgsizecd character varying, IN usr character varying, OUT errcd integer, OUT errmsg character varying) AS
$BODY$
DECLARE
    icd integer;
    cnt integer;
    cntcheck integer;
BEGIN
    --
    -- パラメータチェック
    --

    -- 必須チェック
    IF i_makeritemcd IS NULL THEN
        RAISE EXCEPTION '引数 i_makeritemcd は必須です';
    END IF;
    IF i_imgsizecd IS NULL THEN
        RAISE EXCEPTION '引数 i_imgsizecd は必須です';
    END IF;
    IF i_typediv IS NULL THEN
        RAISE EXCEPTION '引数 i_typediv は必須です';
    END IF;

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

    -- メーカー品番チェック
   SELECT count(itemcd) INTO cnt
       FROM t_item_struct
       WHERE delflg = FALSE
       AND makeritemcd = s_get_nocase_text_lower(i_makeritemcd);
   IF NOT FOUND OR cnt = 0 THEN
        errcd := -11;
        errmsg := '品番「' || i_makeritemcd || '」がありません';
        RETURN;
   ELSIF cnt > 1 THEN
        errcd := -11;
        errmsg := '品番「' || i_makeritemcd || '」の商品が複数あります';
        RETURN;
   ELSE
        SELECT itemcd INTO icd
           FROM t_item_struct
           WHERE delflg = FALSE
           AND makeritemcd = s_get_nocase_text_lower(i_makeritemcd);
   END IF;

   SELECT updcnt INTO cntcheck
       FROM t_image
       WHERE typediv = i_typediv
           AND generalcd = icd
           AND imgsizecd = i_imgsizecd;
   IF NOT FOUND THEN

       -- データがないので追加
       INSERT INTO t_image(typediv, generalcd, generalsubcd, imgsizecd, sellercd, updusrnm, stockcd)
              VALUES    (i_typediv, icd, 0, i_imgsizecd, 0, usr, 0);
   ELSE

       -- データがあるので更新
       UPDATE t_image
          SET updusrnm = usr
        WHERE typediv = i_typediv
           AND generalcd = icd
           AND generalsubcd = 0
           AND imgsizecd = i_imgsizecd
           AND sellercd = 0
           AND stockcd = 0
           AND updcnt = cntcheck;
   END IF;

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

