如何在Postgresql中用逗号分区文本转换为具有列名的表

时间:2017-06-22 08:48:13

标签: sql postgresql

我的文字如下

'id=32702, reservationno=H11985W021216, supconfnumber=-, supitinerary=,'

它应该可以像下面那样访问

select 
  id, 
  reservationno, 
  supconfnumber,
  supitinerary 
from created_table

我使用了以下查询,但没有获取列名。

select a[1], a[2], a[3]
from (
  select string_to_array('id=32702,reservationno=H11985W021216,supconfnumber=-,', ',')
) as dt(a)

3 个答案:

答案 0 :(得分:0)

试试这个:

select
substring(b.a1 from 0 for position('=' in b.a1)) as column1,
substring(b.a2 from 0 for position('=' in b.a2)) as column2,
substring(b.a3 from 0 for position('=' in b.a3)) as column3
from 
(
select a[1] as a1 , a[2] as a2, a[3] as a3 from  string_to_array('id=32702,reservationno=H11985W021216,supconfnumber=-,', ',') a 
) as b

答案 1 :(得分:0)

试试这个:

DO $$
DECLARE 
col1 TEXT;
col2 TEXT;
col3 TEXT;
s_sql TEXT;
BEGIN
select
substring(b.a1 from 0 for position('=' in b.a1)),
substring(b.a2 from 0 for position('=' in b.a2)),
substring(b.a3 from 0 for position('=' in b.a3)) 
INTO col1, col2, col3
from 
(
select a[1] as a1 , a[2] as a2, a[3] as a3 from  string_to_array('id=32702,reservationno=H11985W021216,supconfnumber=-,', ',') a 
) as b;

s_sql := ('select ' || col1 || ', ' || col2 || ', ' || col3 || ' from test');
EXECUTE(s_sql);
END $$;

答案 2 :(得分:0)

你必须做这样的事情,但DO阻止返回void,所以你不能这样直接使用它。这只会动态构造查询文本。

do $$
declare
    s_sql_start text := 'select ';
    s_sql text := s_sql_start;
    _rec record;
begin
    for _rec in (
        select * from (
            select 
            substr(splitedtext, 0, position('=' in splitedtext)) as column_name,
            substr(splitedtext, position('=' in splitedtext)+1) as column_value
            from (
                select trim(regexp_split_to_table(mytext, ',')) as splitedtext
                from (
                select 'id=32702, reservationno=H11985W021216, supconfnumber=-, supitinerary=,'::text as mytext
                ) src
            ) spl
        ) filtered where nullif(column_name,'') is not null)
    loop
        if s_sql<> s_sql_start then
            s_sql := s_sql||', ';
        end if;
        s_sql:=s_sql ||quote_nullable(_rec.column_value)||' as '||_rec.column_name;
    end loop;
    raise notice '%',s_sql; 
    --will only show query text, DO block returns void so you cannot see results from in 
end;
$$