PostgreSQL - Writing dynamic sql in stored procedure that returns a result set
How can I write a stored procedure that contains a dynamically built SQL statement that returns a result set? Here is my sample code: CREATE OR REPLACE FUNCTION reporting.report_get_countries_new ( starts_with varchar, ends_with varchar ) RETURNS TABLE ( country_id integer, country_name varchar ) AS $body$ DECLARE starts_with ALIAS FOR $1; ends_with ALIAS FOR $2; sql VARCHAR; BEGIN sql = 'SELECT * FROM lookups.countries WHERE lookups.countries.country_name >= ' || starts_with ; IF ends_with IS NOT NULL THEN sql = sql || ' AND lookups.countries.country_name <= ' || ends_with ; END IF; RETURN