0

我使用 postgresql 数据库。我想在一个表中插入一行,然后在另一个表中插入另一行,该表的外键与一次 pl/sql 执行中的第一个表相关。

问题是,当我尝试插入第二个表行时,数据库假定我插入到第一个表中的行不存在,因为它尚未提交。我该怎么办?

例子:

REATE OR REPLACE FUNCTION "roomTypeCreate"(character varying, integer)
  RETURNS refcursor AS
$BODY$
DECLARE
curr refcursor;
counter integer;
ids integer[];
current_id integer;
count integer;
BEGIN
    SELECT COUNT(*) INTO counter FROM "RoomType" WHERE LOWER("type"::character varying) = LOWER($1::character varying);

    IF (counter > 0) THEN
        OPEN curr FOR
            SELECT false AS "Status";
        RETURN curr;
    END IF;

    INSERT INTO "RoomType"("type", "creator", "updater") VALUES ($1, $2, $2);
    SELECT currval('"RoomType_id_seq"') INTO current_id;

    SELECT ARRAY(SELECT id FROM "Rate" WHERE id>0) INTO ids;

    count = 1;

    WHILE ids[count] > 0
    LOOP
        INSERT INTO "RoomTypeRate"("type", "rate", "sun", "mon", "tue", "wed", "thu", "fri", "sat", "creator", "updater") VALUES(current_id, ids[count], 99999999, 99999999, 99999999, 99999999, 99999999, 99999999, 99999999, 0, 0);
        count = count + 1;
    END LOOP;

    OPEN curr FOR
        SELECT true AS "Status";
    RETURN curr;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
4

1 回答 1

1

尝试替换:

INSERT INTO "RoomType"("type", "creator", "updater") VALUES ($1, $2, $2);
SELECT currval('"RoomType_id_seq"') INTO current_id;

经过:

INSERT INTO "RoomType"("type", "creator", "updater") VALUES ($1, $2, $2) returning id into current_id;
于 2012-12-17T11:24:48.130 回答