Postgres integer arrays as parameters?
You can always use a properly formatted string. The trick is the formatting.
command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));
Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value))
or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.
In my case, my enumerated type has some values like 'value1'
, 'value2'
, 'value3'
, and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}')
, and this works.
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see
string_to_array
)CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ DECLARE ids INT[]; BEGIN ids = string_to_array($1,','); ... END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 =
'1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ ... END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ ... END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,
SELECT * FROM some_table WHERE id_column = ANY(@id_list)
where @id_list
is bound to an int[]
parameter by way of
command.Parameters.Add("@id_list", NpgsqlDbType.Array|NpgsqlDbType.Integer).Value = my_id_list;
where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).