postgresql - 使用 format() 执行 INSERT 会引发错误

标签 postgresql plpgsql dynamic-sql

尝试执行以下操作:

DO $$
BEGIN
EXECUTE format('INSERT INTO public."EWcfgvars" (idinstrum, varname, enable, subaddr, id_device, id_synchronization_request, pupdate) VALUES (4, %s, 1, 0, 122, 1, 1464022764);', 'test');
  END
$$;

我收到这个错误:

[42703] ERROR: column "test" does not exist
 Where: PL/pgSQL function inline_code_block line 3 at EXECUTE statement

我的 DDL 有什么问题?

最佳答案

占位符 %s 会将参数中的值“按原样”放入字符串中。但是您希望参数被视为文字(常量)。

为此您需要使用占位符 %L:

format('.... (4, <b>%L</b>, 1, 0, 122, 1, 1464022764)', 'test')

对于 execute,您也不需要使用 ; 来终止语句

关于postgresql - 使用 format() 执行 INSERT 会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40410093/

相关文章:

sql - T-SQL : can I use a variable as a database reference

Postgresql JSONB 数组值的内联总和

sql - DROP FUNCTION 不知道参数的数量/类型?

sql - plpgsql 中采用 bigint 的 pseudo_encrypt() 函数

tsql - 用于分页的公用表中的 T-SQL 动态排序依据

sql - 仅选择包含值的列

ruby-on-rails - 在具有可变间隔的日期之间搜索 w/rails

PostgreSQL 恢复备份解决方案

sql - 日期范围之间的 Postgresql 查询

postgresql - 如何创建不返回任何内容的函数