如何将声明类型变量插入 table | Postgres

How to insert declared type variable into table | Postgress

我一直致力于创建一个存储过程,它将 select 来自 table 的数据,对该数据进行一些修改,然后我需要将修改后的数据插入同一个 table。举个例子,我的 table 名字是 student。我的程序如下所示:

create or replace procedure student_create(p_code varchar)
language plpgsql
as $$
declare
   v_student public.student;
begin
    select * into v_student from student where code = p_code and is_latest_version is true;
    raise notice 'Value: %', v_student;
    v_student.id = uuid_generate_v4();
    v_student.version_created_at = now();
    v_student.version_updated_at = v_student.version_created_at;
    raise notice 'Value: %', v_student;
    INSERT INTO public.student VALUES(v_student);
end;$$

我在调用此过程时遇到错误:

ERROR:  column "id" is of type uuid but expression is of type hotel
LINE 1: INSERT INTO public.hotel VALUES(v_hotel)

我知道我可以制作插入语句,就像我可以从变量中获取每个值并将其设置为

INSERT INTO public.student VALUES(v_student.id, v_student.code, v_student.name);

但我不想这样做,因为它会变得紧密耦合,稍后如果我在 table 中添加另一列,那么我也需要将该列添加到此过程中。

有谁知道如何将声明的类型变量直接插入 table。

  1. 没有table类型,只有行复合类型。查看手册 43.3.4。行类型.
  2. 使用行类型。

create or replace procedure student_create(p_code text)
language plpgsql
as $$
declare
   v_student public.student
begin
    for v_student in  select *  from student where code = p_code and is_latest_version is true
    loop
    v_student.id = uuid_generate_v4();
    v_student.version_created_at = now();
    v_student.version_updated_at = v_student.version_created_at;
    v_student.is_latest_version = true;
    v_student.code = p_code;
    INSERT INTO student VALUES(v_student.*);
end loop;
end;$$;

称之为:call student_create('hello');
3.直接使用update子句。

create or replace procedure student_create_1(p_code text)
language plpgsql as $$
BEGIN
    with a  as ( select uuid_generate_v4() as id ,
                       now() as version_created_at,
                       now() as version_updated_at,
                       p_code as "code"   from student 
                where code = p_code and is_latest_version is true)
    
     INSERT INTO student(id, version_created_at, version_updated_at, code) 
            select a.id, a.version_created_at,a.version_updated_at,a."code" from a;
    
end
$$;

称之为:call student_create_1('hello');

fiddle代码:here