下面是我执行一个动态查询的函数,但是我在一个列中得到了此查询的结果,并且所有值都以逗号分隔。
CREATE OR REPLACE FUNCTION get_weather(city text)
RETURNS weather AS $$
DECLARE
rec RECORD;
BEGIN
EXECUTE 'SELECT * FROM weather WHERE city = ''' || city || '''' INTO rec;
RETURN rec;
END;
$$ LANGUAGE plpgsql;
以上功能的结果:
"("San Francisco",46,50,0.25,1994-11-27)"
必需的输出:
请在此帮助我,在此先感谢。
答案 0 :(得分:3)
您必须使用SELECT FROM
SELECT * FROM get_weather('Prague'); postgres=# SELECT * FROM weather ; city │ lo │ hi │ d ────────┼────┼────┼──────────── San Fr │ 46 │ 50 │ 2013-06-06 (1 row) postgres=# SELECT * FROM get_weather('San Fr'); city │ lo │ hi │ d ────────┼────┼────┼──────────── San Fr │ 46 │ 50 │ 2013-06-06 (1 row) postgres=# \sf get_weather CREATE OR REPLACE FUNCTION public.get_weather(city text) RETURNS weather LANGUAGE plpgsql AS $function$ DECLARE rec RECORD; BEGIN EXECUTE 'SELECT * FROM weather WHERE city = $1' INTO rec USING sity; RETURN rec; END; $function$
您的示例中有一些可能的优化
CREATE OR REPLACE FUNCTION get_weather(city text) RETURNS weather AS $$ SELECT * FROM weather WHERE city = $1; $$ LANGUAGE sql;
注意:像你一样构建更新的动态查询!这是SQL注入问题的示例。
改为使用
EXECUTE 'SELECT * FROM weather WHERE city = ' || quote_literal(city) INTO rec;
或更好
EXECUTE 'SELECT * FROM weather WHERE city = $1' INTO rec USING city;