Select 只有一列值基于 table 中的 id 并在 postgresql 函数中使用
Select only one column value based on id from table and use in function in postgresql
描述
我正在创建一个 postgresql 函数并遇到了问题。我正在从 table 读取数据,并根据该数据我是否要更新数据。
但为了选择,我需要创建一个临时 table 或创建另一个 return 单个十进制值的函数。
这是我的代码
Declare command text := 'select distance from road where gid ='|| id;
Execute command;
我卡在这了
我不知道该怎么做,因为我是 postgresql 的新手
我需要什么
我想根据此查询 return 对距离应用条件
例如
IF distance < 100
THEN
(Insert into another table)
END;
我试过的
select distance into varDistance from road where gid ='|| id;
我通过 Select 进入命令并知道这应该与 table 相同。我不接受table。
是否可以使用 double 类型的变量,并且在查询后我得到我的 varibale 初始值?否则解决方案
我不清楚你要做什么,但要从 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()
function to create the SQL string with a placeholder, then use execute
with an into and using clause
l_sql := format('select distance from %I gid = ', l_table_name);
execute l_sql
into l_distance
using p_id; --<< this is the parameter
描述 我正在创建一个 postgresql 函数并遇到了问题。我正在从 table 读取数据,并根据该数据我是否要更新数据。
但为了选择,我需要创建一个临时 table 或创建另一个 return 单个十进制值的函数。
这是我的代码
Declare command text := 'select distance from road where gid ='|| id;
Execute command;
我卡在这了 我不知道该怎么做,因为我是 postgresql 的新手
我需要什么
我想根据此查询 return 对距离应用条件 例如
IF distance < 100
THEN
(Insert into another table)
END;
我试过的
select distance into varDistance from road where gid ='|| id;
我通过 Select 进入命令并知道这应该与 table 相同。我不接受table。
是否可以使用 double 类型的变量,并且在查询后我得到我的 varibale 初始值?否则解决方案
我不清楚你要做什么,但要从 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()
function to create the SQL string with a placeholder, then use execute
with an into and using clause
l_sql := format('select distance from %I gid = ', l_table_name);
execute l_sql
into l_distance
using p_id; --<< this is the parameter