Jam*_*ton 2 postgresql variables function navicat
当我尝试运行自定义 PostgreSQL 函数时出现此错误:
\n\nERROR: query has no destination for result data\nRun Code Online (Sandbox Code Playgroud)\n\nPostgreSQL 函数对我来说非常新。我正在使用 Navicat for PostgreSQL 11.0.17。
\n\n我有一个名为 Translations 的表,其中包含三列:id、english、fran\xc3\xa7ais。以下是我在控制台窗口中创建函数的方法:
\n\ntest=# CREATE FUNCTION add_translation(english varchar(160), fran\xc3\xa7ais varchar(160))\n RETURNS integer \n AS $BODY$\nDECLARE\n translation_id integer;\nBEGIN\n INSERT INTO translations\n ("english", "fran\xc3\xa7ais")\n VALUES (english, fran\xc3\xa7ais)\nRETURNING id\n AS translation_id;\n RETURN translation_id;\nEND;\n$BODY$\nLANGUAGE plpgsql;\nQuery OK, 0 rows affected (0.02 sec)\nRun Code Online (Sandbox Code Playgroud)\n\n当我从控制台窗口调用它时,我收到一条不太有用的错误消息。
\n\ntest=# add_translation(\'one\', \'un\');\nERROR: syntax error at or near "add_translation"\nLINE 1: add_translation(\'one\', \'un\')\n ^\nRun Code Online (Sandbox Code Playgroud)\n\n当我从“设计功能”窗口调用它时,我收到顶部引用的错误。
\n\n我特别想隔离translation_id,因为在这个函数的最终版本中,我想将翻译表中的最新id插入到不同表中的新记录中。
\n\n我也尝试过:
\n\nDECLARE\n translation_id integer;\nBEGIN\n INSERT INTO translations\n ("english", "fran\xc3\xa7ais")\n VALUES (english, fran\xc3\xa7ais);\n SELECT LASTVAL() INTO translation_id;\n RETURN translation_id;\nEND;\nRun Code Online (Sandbox Code Playgroud)\n\n当我从“设计功能”面板运行它时,它的行为正确,但是当我从控制台调用它时,我得到了与以前相同的错误。
\n\n如果您能推荐任何好的教程和示例来了解如何在 postgres 函数中正确使用变量,我将不胜感激。
\n从控制台你需要一个select命令
select add_translation(\'one\', \'un\');\nRun Code Online (Sandbox Code Playgroud)\n\n或者
\n\nselect * from add_translation(\'one\', \'un\');\nRun Code Online (Sandbox Code Playgroud)\n\n你的函数可以是普通的 SQL
\n\ncreate or replace function add_translation (\n english varchar(160), fran\xc3\xa7ais varchar(160)\n) returns integer as $body$\n insert into translations ("english", "fran\xc3\xa7ais")\n values (english, fran\xc3\xa7ais)\n returning id as translation_id;\n$body$ language sql;\nRun Code Online (Sandbox Code Playgroud)\n\n在 plpgsql 中,setof某种类型必须从查询“返回”
create or replace function add_translation (\n english varchar(160), fran\xc3\xa7ais varchar(160)\n) returns setof integer as $body$\nbegin\n return query\n insert into translations ("english", "fran\xc3\xa7ais")\n values (english, fran\xc3\xa7ais)\n returning id as translation_id;\nend;\n$body$ language plpgsql;\nRun Code Online (Sandbox Code Playgroud)\n\n或者要返回单个值,请在 CTE 内插入
\n\ncreate or replace function add_translation (\n english varchar(160), fran\xc3\xa7ais varchar(160)\n) returns integer as $body$\ndeclare\n translation_id integer;\nbegin\n with i as (\n insert into translations ("english", "fran\xc3\xa7ais")\n values (english, fran\xc3\xa7ais)\n returning id\n )\n select id into translation_id from i;\n return translation_id;\nend;\n$body$ language plpgsql;\nRun Code Online (Sandbox Code Playgroud)\n