PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Parametrisiertes ORDER BY und LIMIT in PostgreSQL Table Function

Eine PL/pgSQL-Funktion kann ORDER BY und LIMIT dynamisch und sicher behandeln.

CREATE OR REPLACE FUNCTION get_stuff(_param text, _orderby text, _limit int) RETURNS SETOF stuff AS $func$ BEGIN RETURN QUERY EXECUTE 'SELECT * FROM stuff WHERE col = $1 ORDER BY ' || quote_ident(_orderby) || ' ASC LIMIT $2' USING _param, _limit; END $func$ LANGUAGE plpgsql;

Bezeichner werden mit quote_ident abgesichert, Parameterwerte über USING übergeben.