【问题标题】:How to execute insert statement dynamically如何动态执行插入语句
【发布时间】:2015-03-03 11:38:54
【问题描述】:

我们的数据库是 PostgreSQL 9.3.5。我们需要动态执行插入语句。为此,我们编写了如下代码:

v_seq bigint;
v_levelname varchar(100);
v_cols  text;
v_cols variable having  concatenated data of all column names of particular a table(ex. L150).

L150 table columns details
---------------------------- 
id  bigint;
levelname varchar(100);
healthcareno bigint;
businessno bigint;
bankingno bigint;

v_insertstmt:='insert into L'||levelid||'---tablename(receiving tablename dynamically)
values('||v_seq||','''||v_levelname||''','||v_cols||')';

raise notice '%',v_insertstmt;

数据输出:

insert into L105
values(1053911,''ProductPlanning'','||healthcareno||','||businessno||','||bankingno||')

但healthcareno,businessno,bankingno 这些是列。每一列都有我们需要将这些值插入到表中的值。

v_str:=''''||v_insertstmt||'''';--we added quotes 

提高通知 '%',v_str;

数据输出:

'insert into L105
values(1053911,''ProductPlanning'','||healthcareno||','||businessno||','||bankingno||')'

execute v_str;

但是我们遇到了语法错误。

【问题讨论】:

  • 我很想忽略带有代码片段的 plpgsql 问题,其中只有包含标头的完整函数才能提供必要的上下文。并始终提供逐字错误消息。

标签: postgresql plpgsql dynamic-sql


【解决方案1】:

输出''ProductPlanning'' 错误。请改用USING 子句:

execute format('insert into %I values($1, $2, $3, $4, $5)', 'L' || levelid)
   using v_seq, v_levelname, ... ;

postgres=# create table foo(a int, b text);
CREATE TABLE
postgres=# do $$
postgres$# begin
postgres$# execute format('insert into %I values($1,$2)', 'foo') using 1, 'AHOJ';
postgres$# end;
postgres$# $$;
DO
postgres=# select * from foo;
 a |  b   
---+------
 1 | AHOJ
(1 row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2011-10-07
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2011-03-12
    相关资源
    最近更新 更多