开发者

PostgreSQL: PREPARED statement with ANY($1)

开发者 https://www.devze.com 2023-03-13 17:50 出处:网络
I want to create a PREPARED STATEMENT where inputs are some integers whose count is not known. The way I\'m trying to do is

I want to create a PREPARED STATEMENT where inputs are some integers whose count is not known. The way I'm trying to do is

PREP开发者_开发技巧ARE prep_select_data AS SELECT ARRAY[$1, id], $1, * FROM tbl_data WHERE id = ANY($1);

The error I'm getting is:

ERROR:  op ANY/ALL (array) requires array on right side
LINE 1: ...ELECT ARRAY[$1, id], $1, * FROM tbl_data WHERE id = ANY($1);
                                                             ^

I'm not able to figure out the issue.

Please advise.

Regards,

Mayank


As error says you need to specify your $1 as array (of integers):

-- DEALLOCATE prep_select_data;
PREPARE prep_select_data (int[]) AS 
SELECT
    $1 || ARRAY[id], $1, *
FROM
    tbl_data 
WHERE
    id = ANY($1);

I changed ARRAY[$1, id] to $1 || ARRAY[id], so result looks like:

EXECUTE prep_select_data ('{1, 2}');
 ?column? | ?column? | id | value 
----------+----------+----+-------
 {1,2,1}  | {1,2}    |  1 | aaa
 {1,2,2}  | {1,2}    |  2 | bbb

It's because (from doc):

multidimensional arrays must have matching extents for each dimension. A mismatch causes an error report.

0

精彩评论

暂无评论...
验证码 换一张
取 消