In your scenario, the return type will change due to different column names and types. To handle this, you can take advantage of PostgreSQL's ability to return anonymous record types:
CREATE FUNCTION data_of(integer) RETURNS SETOF record AS ...
However, this approach requires manually specifying column definitions in each function call:
SELECT * FROM data_of(17) AS foo (colum_name1 integer , colum_name2 text , colum_name3 real);
To avoid this tedious approach, you can use document data types like JSON or XML to store unstructured data:
CREATE FUNCTION data_of(integer) RETURNS JSONB AS ...
However, this approach will sacrifice the advantages of PostgreSQL structured data types.
If your data structure is consistent (except for column names), you can return a fixed number of correctly named and typed columns:
CREATE FUNCTION data_of(_id integer) RETURNS TABLE (datahora timestamp, col2 text, col3 text) AS $func$ ...
For simplicity, each column is explicitly converted to type TEXT.
If you have a variable number of columns of the same type, you can use an array to store the values:
CREATE FUNCTION data_of(_id integer) RETURNS TABLE (datahora timestamp, names text[], values float8[]) AS $func$ ...
Also, you can return the column names as an array:
CREATE FUNCTION data_of(_id integer) RETURNS TABLE (datahora timestamp, names text[], values float8[]) AS $func$ ...
To return all columns of a table, regardless of their structure, you can use the anyelement
pseudo data type:
CREATE FUNCTION data_of(_tbl_type anyelement, _id int) RETURNS SETOF anyelement AS $func$ BEGIN RETURN QUERY EXECUTE format(' SELECT * FROM %s -- pg_typeof returns regtype, quoted automatically WHERE id = ORDER BY datahora' , pg_typeof(_tbl_type)) USING _id; END $func$;
Call this function with NULL of the desired table type to dynamically determine the return type:
SELECT * FROM data_of(NULL::pcdmet, 17);
The above is the detailed content of How Can I Handle Dynamic SQL Return Types in PostgreSQL with Varying Column Names and Types?. For more information, please follow other related articles on the PHP Chinese website!