Postgresql:Dyanically构建一个查询字符串

时间:2017-03-20 07:28:25

标签: sql postgresql

我想在postgresql中构建类似下面的字符串

select l1.id, l1.loc, l1.val1 from (select id, loc, val1 from foo where loc = 'loc1') l1
union all
select l2.id, l2.loc, l2.val2 from
(select id, loc, val2 from foo where loc = 'loc1') l2
union all
select l3.id, l3.loc, l3.val3 from
(select id, loc, val3 from foo where loc = 'loc1') l3
union all
select l4.id, l4.loc, l4.val4 from
(select id, loc, val4 from foo where loc = 'loc1') l4;

我怎样才能做到这一点?

我试过了

CREATE OR REPLACE FUNCTION test() RETURNS text AS $str$
DECLARE
 str text:='';
 x text;
 aa text[] := array['l1','l2','l3','l4'];
BEGIN
foreach x in array aa
loop
  str := str ||  x || '.id,' || x ||  '.loc, ' || x || '.val1 ' || ' ' || 'from (select id, loc, val1 from foo where loc =' || quote_indent('loc1') ||')' || ' ' || x;
  raise notice 'value %', str;
end loop;
return str;
END;
$str$ LANGUAGE plpgsq

但不要格式化预期的刺痛。

任何帮助都会非常明显

谢谢你

0 个答案:

没有答案