Una funzione più chiara può restituire direttamente il tipo della tabella:
CREATE OR REPLACE FUNCTION report_get_countries_new(
starts_with text,
ends_with text DEFAULT NULL
)
RETURNS SETOF lookups.countries
AS $func$
DECLARE
sql text := 'SELECT * FROM lookups.countries WHERE country_name >= $1';
BEGIN
IF ends_with IS NOT NULL THEN
sql := sql || ' AND country_name <= $2';
END IF;
RETURN QUERY EXECUTE sql USING starts_with, ends_with;
END
$func$ LANGUAGE plpgsql;Usa USING in EXECUTE: è più sicuro e più efficiente rispetto a inserire valori nella stringa. Fornire un default al secondo parametro permette chiamate più semplici.