tags:

views:

146

answers:

3

Is there a simple way in SQL to convert a string or an array to rows of a table?

For example, let's stay the string is 'a,b,c,d,e,f,g'. I'd prefer an SQL statement that takes that string, splits it at commas and inserts the resulting strings into a table. In PostgreSQL I can use regexp_split_to_array() and split the string into an array. So, if you know a way to insert an array's elements as rows into a table, that would work too.

+1  A: 

I would use string_to_array instead, it's a bit faster :) Regardless though, you can create a table out of it with some generate_series tricks.

CREATE OR REPLACE FUNCTION array_to_table(anyarray)
RETURNS SETOF anyelement AS $$ 
SELECT $1[i] 
FROM generate_series(array_lower($1,1), array_upper($1,1)) g(i);
$$ LANGUAGE SQL STRICT IMMUTABLE;

SELECT * FROM array_to_table(string_to_array('a,b,c,d,e,f,g', ','));
WoLpH
A: 

Generate_series (FROM, TO, STEP) with (1, 7, 2) produces a series 1, 3, 5, 7 which can be used to index the array for substring (COLUMN, INDEX, LEN):

SELECT substring ('a,b,c,d', generate_series (1, 7, 2), 1) AS x ;
 x 
---
 a
 b
 c
 d
user unknown
+3  A: 

To turn an array into a rowset, you can simply use unnest():

SELECT unnest('{1,2,3,4}'::int[])

Which you can then of course combine with regexp_split_to_array, to become:

SELECT unnest(regexp_split_to_array('1,2,3,4', ','))

or as previously mentioned, using string_to_array() instead of regexp_split_to_array() if it's a simple split.

Magnus Hagander
Perhaps it's important to note that `unnest` exists from Postgres 8.4 and up.
WoLpH
Oh yeah, good point.
Magnus Hagander