这是一个修改后的版本,它使用 text[] 数组作为列名来处理多列。它还打印新行和制表符以格式化输出。
CREATE OR REPLACE FUNCTION genhtml(text, text, text, text[])
RETURNS text AS $BODY$
DECLARE
schemaname ALIAS FOR $1;
tablename ALIAS FOR $2;
tabletype ALIAS FOR $3;
columnnames ALIAS FOR $4;
result TEXT := '';
searchsql TEXT := '';
var_match TEXT := '';
col RECORD;
header TEXT;
BEGIN
header := E'\t' || '<tr>' || E'\n';
searchsql := $QUERY$SELECT ''$QUERY$;
FOR col IN SELECT attname
FROM pg_attribute AS a
JOIN pg_class AS c ON a.attrelid = c.oid
WHERE c.relname = tablename
AND n.nspname = schemaname
AND c.relkind = tabletype
AND attnum > 0
AND attname = ANY(columnnames)
LOOP
header := header || E'\t\t' || '<th>' || col || '</th>' || E'\n';
searchsql := searchsql || $QUERY$ || E'\n\t\t' || '<td>' || $QUERY$ || col || $QUERY$ || '</td>' $QUERY$;
END LOOP;
header := header || E'\t' || '</tr>' || E'\n';
searchsql := searchsql || ' FROM ' || schemaname || '.' || tablename;
result := '<table>' || E'\n';
result := result || header;
FOR var_match IN EXECUTE(searchsql) LOOP
IF result > '' THEN
result := result || E'\t' || '<tr>' || var_match || E'\n\t' || '</tr>' || E'\n';
END IF;
END LOOP;
result := result || '</table>' || E'\n';
RETURN result;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
使用以下内容调用该函数:
SELECT genhtml('public', 'tablenamehere', 'r', ARRAY['col1', 'col2', 'col3']);
'r' 用于普通表。如果您使用的是 VIEW,请将其更改为“v”。