CREATE OR REPLACE FUNCTION f_deposit_update(
 IN kubun           integer,    -- 区分
 IN _orderno        integer,    -- 受注No
 IN _depositdate    date,       -- 入金日
 IN _depositdiv     integer,    -- 決済方法区分
 IN _depositstate   integer,    -- ステータス
 IN _cardcompany    varchar,    -- カード会社
 IN _cardnumber     varchar,    -- カード番号
 IN _cardname       varchar,    -- カード名
 IN _cardexp        varchar,    -- 有効期限
 IN _shitennumberkey       varchar,    -- 支店番号
 IN _kouzanumberkey        varchar,    -- 口座番号

 IN upduser         varchar,
 IN pc              varchar,
 IN count           integer,

 OUT errcd          integer,
 OUT errmsg         varchar,
 OUT code           integer) 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 (2,3) THEN
        SELECT updcnt INTO cntcheck FROM t_deposit WHERE orderno = _orderno;
        IF NOT FOUND OR cntcheck <> count THEN
            RAISE EXCEPTION '更新カウンタが不正です';
        END IF;
    END IF;
    IF kubun = 1 THEN
        -- 受注明細追加
        insert into t_deposit (
            orderno,
            depositdate,
            depositdiv,
            depositstate,
            cardcompany,
            cardnumber,
            cardname,
            cardexp,
            shitennumberkey,
            kouzanumberkey,
            updusrnm,
            updpcnm
        ) values (
            _orderno,
            _depositdate,
            _depositdiv,
            _depositstate,
            _cardcompany,
            _cardnumber,
            _cardname,
            _cardexp,
            _shitennumberkey,
            _kouzanumberkey,
            upduser,
            pc
        );

        errcd := 1;
        code := _orderno;
        errmsg := '完了';
        RETURN;

    ELSIF kubun = 2 THEN
        -- 受注明細変更
        UPDATE t_deposit SET
            depositdate = _depositdate,
            depositdiv = _depositdiv,
            depositstate = _depositstate,
            cardcompany = _cardcompany,
            cardnumber = _cardnumber,
            cardname = _cardname,
            cardexp = _cardexp,
            shitennumberkey = _shitennumberkey,
            kouzanumberkey = _kouzanumberkey,

            updusrnm = upduser,
            updpcnm = pc
            WHERE orderno = _orderno;
        errcd := 1;
        code := _orderno;
        errmsg := '完了';
        RETURN;

    ELSIF kubun = 3 THEN
        -- 受注明細削除
        UPDATE t_deposit SET
            delflg = TRUE,
            updusrnm = usr,
            updpcnm = pc
            WHERE orderno = _orderno;

        errcd := 1;
        code := _orderno;
        errmsg := '完了';
        RETURN;
    END IF;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
