说明我正在创建postgresql函数并遇到问题。我正在从表中读取数据,并根据我想要更新数据的数据。
但是对于选择,我需要创建临时表或创建另一个返回单个十进制值的函数。
这是我的代码
Declare command text := 'select distance from road where gid ='|| id;
Execute command;
我被困在这一点上我不知道该怎么办,因为我是postgresql的新手
我需要的
我想在这个查询返回的距离上应用条件,例如
IF distance < 100
THEN
(Insert into another table)
END;
我尝试了什么
select distance into varDistance from road where gid ='|| id;
我通过Select Into命令来了解这应该与table相同。这是我不能接受的。
这可能有双类型变量,在查询后我得到我的变量初始化值?或者解决方案
我不清楚你要做什么,但要从表中读取单个值,你需要select into
一些事情:
create function some_function(p_id integer)
returns ...
as
$$
declare
l_distance double precision;
begin
select distance
into l_distance
from road
where id = p_id; --<< this is the parameter
if l_distance < 100 then
insert into some_other_table (...)
values (...)
end if;
end;
$$
language plpgsql;
根据您提供的少量信息,我看不出任何动态SQL的原因。
如果确实需要动态SQL,请使用format()
函数创建带占位符的SQL字符串,然后使用execute
with an into and using clause
l_sql := format('select distance from %I gid = $1', l_table_name);
execute l_sql
into l_distance
using p_id; --<< this is the parameter