UPDATE a whole row in PL/pgSQL

前端 未结 3 1904
南旧
南旧 2021-01-19 06:33

I have plpgsql function:

CREATE OR REPLACE FUNCTION test() RETURNS VOID AS
$$
DECLARE
    my_row my_table%ROWTYPE;
BEGIN
    SELECT * INTO my_row FROM my_tab         


        
3条回答
  •  借酒劲吻你
    2021-01-19 07:05

    I managed to get this working in PLPGSQL in a couple of lines of code.

    Given a table called table in a schema called example, and a record of the same type declared as _record, you can update all the columns in the table to match the record using the following hack:

    declare _record example.table;
    
    ...
    
    -- get the columns in the correct order, as a string
    select string_agg(format('%I', column_name), ',' order by ordinal_position)
      into _columns
      from information_schema.columns
      where table_schema='example' and table_name='table';
    
    execute 'update example.table set (' || _columns || ') = row($1.*) where pkey=$2'
      using _record, _record.pkey;
    

    In the above example, of course, _record.pkey is the table's primary key.

提交回复
热议问题