在Postgresql中动态创建TEMP TABLE并在FOR循环中选择相同的表。但是在PIPE符号附近得到错误

时间:2017-01-16 09:48:12

标签: postgresql plpgsql postgresql-9.3 postgresql-9.4

do
$xyz$
declare
y text;
i record;
begin
y := to_char(current_timestamp, 'YYYYMMDDHHMMSS');
raise notice '%',y;
execute 'CREATE TEMP TABLE someNewTable' 
  ||y
  ||' AS select * from ( VALUES(0::int,-99999::numeric), (1::int,       100::numeric)) as t (key, value)';

    for i in (select * from someNewTable||y) loop
     raise notice '%',i.key;
    end loop;
   end;
  $xyz$ language 'plpgsql'


 ERROR:  syntax error at or near "||"
LINE 13:    for i in (select * from someNewTable||y) loop

我无法理解为什么误差在PIPE符号处。请帮我。我一直在尝试Oracle数据库,但同样的错误。我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

for ... loop语句中的查询也必须是动态的,因此您应该使用execute两次。

使用format()功能,与execute

配合使用非常方便
do $xyz$
declare
    y text;
    i record;
begin
    y := to_char(current_timestamp, 'YYYYMMDDHHMMSS');
    raise notice '%', y;
    execute format($ex$
        create temp table somenewtable%s
        as select * from (
            values
                (0::int, -99999::numeric), 
                (1::int, 100::numeric)
            ) as t (key, value)
        $ex$, y);

    for i in 
        execute format($ex$
            select * from somenewtable%s
            $ex$, y)
    loop
        raise notice '%',i.key;
    end loop;
end;
$xyz$ language 'plpgsql';