-- 名称テーブル 更新
-- DROP FUNCTION f_name_update(kubun int4, code int4, _name "varchar", _namediv "varchar", disp int4, upduser "varchar", pc "varchar", count int4);


CREATE OR REPLACE FUNCTION f_name_update(
    kubun       integer,
    code        integer,
    _name        character varying,
    _namediv     integer,
    disp        integer,
    upduser     character varying,
    pc          character varying,
    count       integer)
RETURNS integer AS
$$
DECLARE
    cntcheck integer;
BEGIN
    --
    -- パラメータチェック
    --

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

    -- 必須チェック
    IF _namediv IS NULL THEN
        RAISE EXCEPTION '引数 namediv は必須です';
    END IF;
    IF kubun IN (2,3) THEN
        IF code IS NULL THEN
            RAISE EXCEPTION '引数 code は必須です';
        END IF;
        IF count IS NULL THEN
            RAISE EXCEPTION '引数 count は必須です';
        END IF;
    END IF;

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

    -- 更新カウンタチェック
    IF kubun IN (2,3) THEN
        SELECT updcnt INTO cntcheck FROM t_name WHERE namediv = _namediv AND namecd = code;
        IF NOT FOUND OR cntcheck <> count THEN
            RETURN -11;
        END IF;
    END IF;


    --
    -- 更新処理
    --

    -- 追加
    IF kubun = 1 THEN
        INSERT INTO t_name(namediv, namecd, name, disppriority, updusrnm, updpcnm)
               VALUES(_namediv, code, _name, disp, upduser, pc);

    -- 更新
    ELSIF kubun = 2 THEN
        UPDATE t_name
           SET name = _name,
               disppriority = disp,
               updusrnm = upduser,
               updpcnm = pc
         WHERE namediv = _namediv AND namecd = code;

    -- 削除
    ELSIF kubun = 3 THEN
        DELETE FROM t_name
         WHERE namediv = _namediv AND namecd = code;
    END IF;

    RETURN 1;
END;
$$
LANGUAGE 'plpgsql' VOLATILE;
