0

I'm trying to pass in a list of values into a Postgres 11 procedure. The query has an IN condition. How do I pass in a list of values to the procedure & then how do I use it in the query?

create or replace procedure some_procedure(
  source_id_list character varying  <-- is this correct?
  )
language plpgsql
as $$
declare
  result_count int;
begin
select count(*)
into result_count
from table sd
where sd.id in source_id_list  <-- syntax error
;
RAISE NOTICE 'result: %', result_count;
end;
$$
1
  • IN accepts a list of values, you are giving it a string. Why not use an array as an argument to the function instead? Commented Oct 1, 2020 at 23:01

1 Answer 1

2

IN expects a list of values, while you are giving it a string.

If you can change the datatype of the argument to the procedure, then it would be simpler to use an array:

create or replace procedure some_procedure(source_id_list int[])
language plpgsql
as $$
declare
    result_count int;
begin
    select count(*)
    into result_count
    from table sd
    where id = any(source_id_list);
    
    raise notice 'result: %', result_count;
end;
$$

If you can't change the argument of the datatype, then another option uses string_to_array() to parse the string as an array:

select count(*)
into result_count
from table sd
where sd.id = any(string_to_array(source_id_list, ',')::int[]);
Sign up to request clarification or add additional context in comments.

2 Comments

those are great solutions. how do I pass in a list? in my case, the ids are strings, ` source_id_list character varying[] := ('5f697ecb9ddf7744a7a1f935');` gives me error: ERROR: malformed array literal: "5f697ecb9ddf7744a7a1f935" DETAIL: Array value must start with "{" or dimension information. thanks
@FooL: ARRAY['5f697ecb9ddf7744a7a1f935']

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.