示例代码删去了最基本的部分以演示问题:

CREATE OR REPLACE FUNCTION mytest4() RETURNS TEXT AS $$
DECLARE
   wc_row wc_files%ROWTYPE;
   fieldName TEXT;
BEGIN
    SELECT * INTO wc_row FROM wc_files WHERE "fileNumber" = 17117;
 -- RETURN wc_row."fileTitle"; -- This works. I get the contents of the field.
    fieldName := 'fileTitle';
 -- RETURN format('wc_row.%I',fieldName); -- This returns 'wc_row."fileTitle"'
                                          -- but I need the value of it instead.
    RETURN EXECUTE format('wc_row.%I',fieldName); -- This gives a syntax error.
 END;
$$ LANGUAGE plpgsql;

在这种情况下,如何获取动态生成的字段名的值?

最佳答案

对函数to_json()使用技巧,对于复合类型,该函数返回一个以列名为键的json对象:

create or replace function mytest4()
returns text as $$
declare
   wc_row wc_files;
   fieldname text;
begin
    select * into wc_row from wc_files where "filenumber" = 17117;
    fieldname := 'filetitle';
    return to_json(wc_row)->>fieldname;
end;
$$ language plpgsql;

关于postgresql - 如何获取PL/pgSQL中动态生成的字段名称的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39808133/

10-11 02:58