postgresql – postgres中的动态sql查询
发布时间:2020-12-13 16:33:47 所属栏目:百科 来源:网络整理
导读:我试图使用动态SQL在postgres中运行一些查询. 例: EXECUTE format('SELECT * from result_%s_table',quote_ident((select id from ids where condition = some_condition))) 我必须查询一个表,其格式为result_%s_table,其中,我需要从另一个表中替换正确的
我试图使用动态SQL在postgres中运行一些查询.
例: EXECUTE format('SELECT * from result_%s_table',quote_ident((select id from ids where condition = some_condition))) 我必须查询一个表,其格式为result_%s_table,其中,我需要从另一个表中替换正确的表名(一个id). 我得到错误ERROR:准备语句“格式”不存在 链接:string substitution with query result postgresql
EXECUTE …使用仅在
PL/PgSQL中工作 – 即在PL / PgSQL语言中编写的函数或
DO blocks中.它在纯SQL中不起作用;执行准备语句时,纯SQL中的EXECUTE是完全不同的.您不能直接在PostgreSQL的SQL方言中使用动态SQL.
比较: > PL/PgSQL’s 参见my prior answer的第二个最后一个. 除了在PL / PgSQL中不运行,你的SQL语句是错误的,它不会做你期望的.如果(select id from ids where condition = some_condition)返回为42,则如果id为整数,则该语句将失败.如果它被转换成文字,你会得到: EXECUTE format('SELECT * from result_%s_table',quote_ident('42')); EXECUTE format('SELECT * from result_%s_table','"42"'); EXECUTE 'SELECT * from result_"42"_table'; 这无效你实际上想要result_42_table或“result_42_table”.你必须写一些更像: EXECUTE format('SELECT * from %s',quote_ident('result_'||(select id from ids where condition = some_condition)||'_table')) 如果你必须使用quote_ident. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |