开发者

SQL: convert tokens in a string or elements of an array into rows of a table

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 woul开发者_开发问答d work too.


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.


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', ','));


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜