簡體   English   中英

在 PostgreSQL 中插入具有串行主鍵列的行類型

[英]Inserting row types with a serial primary key column in PostgreSQL

我想要一個簡單的 function,它接收所有記錄列並在不存在時創建它們。 這里的表只是一個虛擬表,我的觀點更多是關於在使用行類型插入數據時必須如何處理 id (SERIAL) 列。

CREATE TABLE
  some_table (
    "id" SERIAL PRIMARY KEY,
    "some_value" VARCHAR NOT NULL
  );
declare
    r_some_table_rt some_table%rowtype;
begin
    select *
    into r_some_table_rt
    from some_table
    where some_column = 'Some value';

  if r_some_table_rt.id is null then
    -- Tried without assigning r_some_table_rt.id
    -- r_some_table_rt.id := default; -- Tried this
    -- r_some_table_rt.id := currval(pg_get_serial_sequence('some_table', 'id')); -- And this
    r_some_table_rt.some_column := 'Some other value';

    insert into some_table
    values (r_some_table_rt.*)
    returning id into r_some_table_rt.id;

  end if;

  return r_some_table_rt.id;
end;

PostgresError: null value in column "id" of relation "some_table" violates not-null constraint

我嘗試了以下

  1. 使用普通的插入效果非常好: insert into some_table (some_column) values ('Some value'); .
  2. r_some_table.id:= default; -> PostgresError: DEFAULT is not allowed in this context
  3. r_some_table.id:= currval(pg_get_serial_sequence('some_table', 'id')); -> PostgresError: currval of sequence "some_table_id_seq" is not yet defined in this session

這對我有用:

r_some_table_rt.id:= nextval(pg_get_serial_sequence('some_table', 'id'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM