Postgresql动态游标(用于EXECUTE中的记录),字段访问

时间:2017-03-12 09:56:58

标签: postgresql cursor plpgsql dynamic-sql

假设下面的块:

do $$
declare
v_table_name text:='table_name';
v_column_name text:='column_name';
v_record record;
v_sql_dynamic text;
v_enum_xml xml;
v_string text;
begin
  v_sql_dynamic:=format('select %s from %s',v_column_name,v_table_name);
  FOR v_record IN EXECUTE v_sql_dynamic
  LOOP
   raise notice 'field with name % has a value of %',v_column_name,***?????***;
  END LOOP;
end;
$$ language plpgsql

如何以v_record.v_column_name的方式访问v_record字段?

1 个答案:

答案 0 :(得分:0)

See Abelisto's comment.无论如何,在将值转换为text时,to_json()已经足够好并且速度稍快。

DO
$$
DECLARE
   v_table_name   text := 'table_name';
   v_column_name  text := 'column_name';
   v_sql_dynamic  text := format('select %s from %s', v_column_name, v_table_name);
   v_record       record;
BEGIN
   FOR v_record IN EXECUTE v_sql_dynamic
   LOOP
      RAISE NOTICE 'field named % has value %.'
    , v_column_name, to_json(v_record) ->> v_column_name;
   END LOOP;
END
$$ LANGUAGE plpgsql;

相关: