0

Basically I need to create a function for a website guy to call a query search, he inputs an id and I need to return a number of ids from other tables that intersect with that id

My function is (doesnt work)

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;

The idea is to have the $1 being the variable that the user wants to search for. I need to return the object id and object class but keep running into errors

ERROR: column reference "id" is ambiguous
Detail: It could refer to either a PL/pgSQL variable or a table column.

How to make this work?

1
  • Just to be sure, you should name your parameter p_id or so, it's a match for id, too... Commented Mar 24, 2021 at 19:49

1 Answer 1

1

The preferred way it to rename the parameter:

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;

Another way is to qualify the column reference (e.g. by using a table alias):

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;

Note that I also changed the function to language sql which is typically more efficient for simple functions wrapping a query.

Sign up to request clarification or add additional context in comments.

4 Comments

It worked thanks! Though is there a way to output the result as a table? I'm getting the output (just, like, this) in one column
You need to use select * from return_id(...)
you mean returns table (derpid integer, object text) as $function$ select * from ( x.objectid, x.object_class from ( .... ) x ) y ?
No. When you use the function, use it like a table. select * from ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.