だからここに私の更新機能があります:
CREATE OR REPLACE FUNCTION api.book_update(
in_id BIGINT,
in_category VARCHAR,
in_published DATE,
in_author VARCHAR,
in_name VARCHAR
) RETURNS VOID AS $$
DECLARE
in_category_id BIGINT;
tmp BIGINT;
BEGIN
SELECT COUNT(*) INTO tmp FROM schemas.book;
IF (NOT (tmp <> 0)) THEN
RETURN;
END IF;
SELECT
category_id
INTO
in_category_id
FROM
schemas.book
WHERE
id = in_id;
SELECT category_id INTO tmp FROM schemas.category WHERE name = in_category;
IF (NOT FOUND)
THEN
SELECT nextval('schemas.category_category_id_seq') INTO tmp;
UPDATE schemas.book
SET
category_id = tmp,
published = in_published,
author = in_author,
name = in_name
WHERE
id = in_id;
INSERT INTO schemas.category (
category_id,
name
) VALUES (
tmp,
in_category
);
ELSE
SELECT category_id INTO tmp FROM schemas.category WHERE name = in_category;
UPDATE schemas.book
SET
category_id = tmp,
published = in_published,
author = in_author,
name = in_name
WHERE
id = in_id;
END IF;
END;
$$
LANGUAGE plpgsql;
端末出力:
pgdb=# select * from api.book_add('aaa', '10-12-13', 'Aauthor','Name');
book_add
----------
(1 row)
pgdb=# select * from api.book_list;
id | category | published | author | name
----+----------+------------+---------+------
1 | aaa | 2013-10-12 | Aauthor | Name
(1 row)
pgdb=# select * from api.book_update(1, 'bbb', '10-12-13', 'Aauthor','Name');
ERROR: insert or update on table "category" violates foreign key constraint "category_category_id_fkey"
DETAIL: Key (category_id)=(2) is not present in table "book".
CONTEXT: SQL statement "INSERT INTO schemas.category (
category_id,
name
) VALUES (
tmp,
in_category
)"
PL/pgSQL function "book_update" line 31 at SQL statement
pgdb=#
「本」でcategory_idをtmpに更新し、その後このtmpを「category」テーブルに挿入すると、なぜ存在しないのですか?
ここに完全なスキーマスクリプト
があります。