如何在PostgreSQL函数中运行多个动态查询
我遇到了一些问题,弄清楚如何在单个功能中运行多个动态查询。
CREATE OR REPLACE FUNCTION cnms_fy22q2.test_function(
fyq text)
RETURNS void
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$
BEGIN
-- logic
TRUNCATE TABLE 'schema_' || fyq || '.my_table'
DROP TABLE 'schema_' || fyq || '.my_table';
END;
$BODY$;
我通常会遇到语法错误,例如错误:或附近...
的语法错误。我在这里做错了什么?
I am having some issues figuring out how to run multiple dynamic queries in a single function.
CREATE OR REPLACE FUNCTION cnms_fy22q2.test_function(
fyq text)
RETURNS void
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$
BEGIN
-- logic
TRUNCATE TABLE 'schema_' || fyq || '.my_table'
DROP TABLE 'schema_' || fyq || '.my_table';
END;
$BODY$;
I am generally getting syntax errors, like ERROR: syntax error at or near ...
. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能简单地将串联字符串做出动态的SQL语句。看看 eccepute 和立即执行。
就您而言,您可以这样使用:
You can't simply concatenate strings to make a dynamic sql statement. Take a look at EXECUTE and EXECUTE IMMEDIATE.
In your case, you could use it like this:
使用将返回字符串并在您的函数中执行的格式函数。
sqldaddy.io
Use the format function which will return a string and execute in your function.
Demo in sqldaddy.io
只是为了添加我提出的第三个选项,该选项结合了单个
execute format();
语句中的查询,这是我想到的:Just to add a third option that I came up with which combines the queries inside a single
EXECUTE format();
statement, here's what I came up with: