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

标签 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 数据库中尝试,但同样的错误。我在这里做错了什么吗?

最佳答案

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

关于postgresql - 在 Postgresql 中动态创建 TEMP TABLE 并在 FOR 循环中选择相同的表。但是在 PIPE 符号附近出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41673493/

相关文章:

postgresql - 将 “previous row” 值与 SELECT 语句中的现有行值相加

macos - 无法在 Mac OS 启动时加载 postgresql

PostgreSQL COPY,是否可以一次将数据写入多个表

arrays - postgres,多维数组的包含运算符在比较之前执行展平?

function - 需要有关 Postgres 触发器和功能的帮助

sql - 我们可以在 plpgsql 函数的 begin-end block 中声明变量吗?

postgresql - 如何在 plpgsql 函数中获取表的关键字段?

PostgreSQL 设置 PGDATA 变量

sql - 选择 case when number 然后在 postgresql 中选择 char

node.js - Sequelize插入连接表(多对多)