CREATE OR REPLACE FUNCTION f_import_cast_item2(IN itemcode integer, IN castcode integer[], IN castname character varying[], IN usr character varying, OUT errcd integer, OUT errmsg character varying) AS
$BODY$

DECLARE
     cast integer;
	 cnt integer;
     i   integer;
     flg integer;
BEGIN
    errcd := 1;
    i := 1;

    IF itemcode IS NULL THEN
        errmsg := '品目コードが指定されていません。';
        errcd := -10;
        RETURN;
    END IF;

    IF usr IS NULL THEN
        errmsg := '更新ユーザが指定されていません。';
        errcd := -10;
        RETURN;
    END IF;

    LOOP
        flg := 1;
        IF castcode[i] = 0 AND castname[i] = 'NULL' THEN
            flg := 0;
        ELSIF castcode[i] <> 0 THEN
            SELECT castcd INTO cast FROM t_cast WHERE castcd = castcode[i] AND castdiv=2;
            IF cast IS NULL THEN
                errmsg := castcode[i] || 'はキャストマスタにありません2';
                errcd := -10;
                RETURN;
            END IF;

        ELSIF castcode[i] = 0 THEN
            -- キャスト名からキャストコード取得
            SELECT castcd INTO cast FROM t_cast WHERE castnm = castname[i] AND castdiv=2;
            IF cast IS NULL THEN
                errmsg := castname[i] || 'はキャストマスタにありません2';
                errcd := -10;
                RETURN;
            END IF;
        END IF;

        -- 追加(重複しない)
		SELECT count(*) INTO cnt FROM t_cast_item WHERE itemcd=itemcode AND castcd=cast;
		IF cnt <= 0 AND flg = 1 THEN
            INSERT INTO t_cast_item(castcd, itemcd, updusrnm) VALUES(cast, itemcode, usr);
		END IF;

        -- ループ終了
        i := i + 1;
        IF castcode[i] IS NULL AND castname[i] IS NULL THEN
            EXIT;
        END IF;

    END LOOP;
    errcd := 1;
END;

$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

