用未绑定的 PostgreSQL 游标完全替换记录

Fully replace a record with unbound PostgreSQL cursor

是否可以使用未绑定的游标来完全编辑和替换 table 中的行?

我使用未绑定游标,因为 table 是用参数动态指定的,但我不能使用 "UPDATE table SET column = value WHERE" 语法,因为列未指定。

CREATE OR REPLACE FUNCTION trim_table(in_table TEXT) AS $$
  DECLARE
    ref REFCURSOR;
    current_row RECORD;
BEGIN
  OPEN ref FOR EXECUTE 'SELECT * FROM '|| quote_ident(in_table);
  LOOP
    FETCH ref INTO current_row;
    EXIT WHEN NOT FOUND;
    current_row = my_row_function(current_row);
    /*How can I replace my row here?*/
  END LOOP;
  CLOSE ref;
END
$$ LANGUAGE plpgsql;

我找到的所有示例和答案仅显示如何更新单个字段而不是完整记录。

我认为这段代码可以在某些方面帮助您:

select 
    string_agg('UPDATE '||table_schema||'.'||table_name||chr(13)||' SET '||column_name||' = TRIM('||column_name||')', '; '||chr(13)) into query
from information_schema.columns
where data_type in ('varchar', 'text')
    and table_schema = 'your_schema'
    and table_name = 'your_table_name';

execute query;

把它放在你的程序中,修改到你方便的地方,你就不再需要这个循环了。