Thread: MySql Concat function equivalent
Is there any way to create a postgresql function that would take unlimited parameters like mysql's concat()? Currently my application was calling the concat function with parameters comming from php...something like "select concat(".implode(',',array)."). So without having a predefined number of parameters, I would need a function that could be able to concatenate the fields no matter how many they are. Is this possible? |
On 9 November 2010 13:46, Vaduvoiu Tiberiu <vaduvoiutibi@yahoo.com> wrote:
Is there any way to create a postgresql function that would take unlimited parameters like mysql's concat()? Currently my application was calling the concat function with parameters comming from php...something like "select concat(".implode(',',array)."). So without having a predefined number of parameters, I would need a function that could be able to concatenate the fields no matter how many they are. Is this possible?
Which version of PostgreSQL are you on? If you're on >= 8.4 you can use these to simulate it:
CREATE FUNCTION concat(VARIADIC arr anyarray) RETURNS text AS $$
SELECT array_to_string($1, '');
$$ LANGUAGE SQL;
CREATE FUNCTION concat_ws(delim text, VARIADIC arr anyarray) RETURNS text AS $$
SELECT array_to_string($2, $1);
$$ LANGUAGE SQL;
Then you can run:
SELECT concat(1,2,3);
to get:
123
or:
SELECT concat_ws('-',1,2,3);
to get:
1-2-3
Note that all elements of the array you're passing in have to be the same type. And 9.1 should have this a better version of this functionality built in: http://developer.postgresql.org/pgdocs/postgres/functions-string.html
Hope that helps.
--
Thom Brown
Twitter: @darkixion
IRC (freenode): dark_ixion
Registered Linux user: #516935