對於您的用例,您可以使用hstore或兩個數組或二維數組。你的例子很好地演示了SQL注入,所以你不應該忘記必要的轉義。
CREATE OR REPLACE FUNCTION hstore_params(filters hstore)
RETURNS text AS $$
BEGIN
RETURN 'SELECT * FROM some_table ' ||
coalesce ('WHERE ' ||
(SELECT string_agg(quote_ident(key) || ' = ' || quote_literal(value), ' and ')
FROM each('c1 => Ahoj, c2 => Nazdar'::hstore). ''));
END;
$$ LANGUAGE plpgsql;
postgres=# SELECT hstore_params('c1 => Ahoj, c2 => Nazdar');
hstore_params
--------------------------------------------------------------
SELECT * FROM some_table WHERE c1 = 'Ahoj' and c2 = 'Nazdar'
(1 row)
接着可能性的函數默認參數使用。這是我個人最喜歡的:
CREATE OR REPLACE FUNCTION hstore_params(c1 text DEFAULT NULL, c2 text DEFAULT NULL)
RETURNS text AS $$
BEGIN
EXECUTE 'SELECT *
FROM xx
WHERE (c1 = $1 OR c1 IS NULL)
AND (c2 = $2 OR c2 IS NULL)'
USING c1, c2;
RETURN 'ok';
END;
$$ LANGUAGE plpgsql;
postgres=# SELECT hstore_params();
hstore_params
---------------
ok
(1 row)
postgres=# SELECT hstore_params('Ahoj','Nazdar');
hstore_params
---------------
ok
(1 row)
postgres=# SELECT hstore_params('Ahoj');
hstore_params
---------------
ok
(1 row)
postgres=# SELECT hstore_params(c2 := 'Ahoj');
hstore_params
---------------
ok
(1 row)
退房'hstore' http://www.postgresql.org/docs/current/static/hstore.html – 2014-10-07 17:34:43