sql - 用作查询变量以返回结果的函数
问题描述
基本上我需要为网站人员创建一个函数来调用查询搜索,他输入一个 id,我需要从与该 id 相交的其他表中返回一些 id
我的功能是(不起作用)
create or replace function return_id (id integer)
returns table (derpid integer, object text)
as $function$
begin
RETURN QUERY
select x.objectid, x.object_class
from (
select objectid, object_class from table1 a where st_intersects(a.geom, (select geometry from searchtable where id = $1) ) and st_length(st_intersection(a.geom, (select geometry from ftth.cable where id = $1))) > 1
) x ;
end;
$function$ language plpgsql VOLATILE
COST 100;
这个想法是让 $1 成为用户想要搜索的变量。我需要返回对象 ID 和对象类,但不断遇到错误
ERROR: column reference "id" is ambiguous
Detail: It could refer to either a PL/pgSQL variable or a table column.
如何使这项工作?
解决方案
重命名参数的首选方式:
create or replace function return_id (p_id integer)
returns table (derpid integer, object text)
as $function$
select x.objectid, x.object_class
from (
select objectid, object_class
from table1 a
where st_intersects(a.geom, (select geometry from searchtable where id = p_id) )
and st_length(st_intersection(a.geom, (select geometry from ftth.cable where id = p_id))) > 1
) x ;
$function$
language sql
stable;
另一种方法是限定列引用(例如,通过使用表别名):
create or replace function return_id (id integer)
returns table (derpid integer, object text)
as $function$
select x.objectid, x.object_class
from (
select objectid, object_class
from table1 a
where st_intersects(a.geom, (select geometry from searchtable st where st.id = $1) )
and st_length(st_intersection(a.geom, (select geometry from ftth.cable c where c.id = $1))) > 1
) x ;
$function$
language sql
stable;
请注意,我还更改了language sql
对于包装查询的简单函数通常更有效的函数。
推荐阅读
- cassandra - 修改 cqlsh 提示符以获取唯一标识符
- java - 如何从其他类制作的按钮对象中获取来源'
- html - 如何制作一个可根据设备屏幕调整大小的侧导航栏(并在其旁边制作一个顶部导航栏)?
- javascript - 弹出窗口没有显示我想要的照片
- haskell - 尝试编写 Haskell 函数以获取字符串参数并附加到文件
- react-native - react-native:具有动态 numColumns 的平面列表,取决于 json 参数
- resharper - 我无法禁用的 Visual Studio 2019 / Resharper 令人发狂的自动格式化行为
- pandas - 使用“set_dataframe”时的“UnicodeEncodeError”
- google-apps-script - 插入新行并仅从下一行复制数据验证
- python-3.x - 为什么减少要求参数的函数