如何创建一个返回值的 postgres 函数

Ris*_*ran 3 postgresql insert functions

我正在尝试将一些网络应用程序逻辑转移到 postgres 函数中。但是我在创建一个非常基本的插入函数时遇到了一些错误。

这是我正在尝试创建的功能;

CREATE OR REPLACE FUNCTION create_user(IN email EMAIL, password TEXT, thumb TEXT)
RETURNS text AS 
$BODY$
BEGIN
   insert into users (unqid, thumb, email, password) 
   values (gen_random_uuid(), thumb, email, password)
   returning unqid ;
END;
$BODY$
  LANGUAGE plpgsql
  VOLATILE
Run Code Online (Sandbox Code Playgroud)

如果插入成功,我试图让函数返回项目的 uuid。我这样称呼它;

select * from create_user('newuser@mail.com', 'passpopcorn', 'thumbelinaurl');
Run Code Online (Sandbox Code Playgroud)

收到此错误;

SQL Error [42601]: ERROR: query has no destination for result data
  Where: PL/pgSQL function create_user(email,text,text) line 3 at SQL statement
Run Code Online (Sandbox Code Playgroud)

从我的谷歌搜索看来,当查询中没有 return 语句时,似乎会出现此错误。但在我的插入查询中,我确实有一个返回语句。

额外问题;对于简单的插入语句(例如这里的这个语句,或者带有几个选择后跟一个插入的语句),函数或过程会是更好的选择吗?

mus*_*cio 6

SQL 错误 [42601]:错误:查询没有结果数据的目标

insert ... returning ...生成一个结果集,其中包含子句中引用的列returning。在 PL/pgSQL 块中,必须以某种方式处理结果集。您有三个选择:

  • 中间变量

      CREATE OR REPLACE FUNCTION create_user(IN email EMAIL, password TEXT, thumb TEXT)
      RETURNS VARCHAR(40) AS 
      $BODY$
      DECLARE id VARCHAR(40);
      BEGIN
         insert into users (unqid, thumb, email, password) 
         values (gen_random_uuid(), thumb, email, password)
         returning unqid INTO id;
         RETURN id;
      END;
      $BODY$
        LANGUAGE plpgsql
        VOLATILE  
    
    Run Code Online (Sandbox Code Playgroud)
  • return query,这避免了额外的变量

      CREATE OR REPLACE FUNCTION create_user(IN email EMAIL, password TEXT, thumb TEXT)
      RETURNS TABLE (id VARCHAR(40)) AS 
      $BODY$
      BEGIN
         RETURN QUERY 
         insert into users (unqid, thumb, email, password) 
         values (gen_random_uuid(), thumb, email, password)
         returning unqid;
      END;
      $BODY$
        LANGUAGE plpgsql
        VOLATILE  
    
    Run Code Online (Sandbox Code Playgroud)
  • 一个简单的 SQL 函数,在您的情况下我更喜欢它,因为您不需要任何 PL/pgSQL 功能

      CREATE OR REPLACE FUNCTION create_user(IN email EMAIL, password TEXT, thumb TEXT)
      RETURNS TABLE (id VARCHAR(40)) AS 
      $BODY$
         insert into users (unqid, thumb, email, password) 
         values (gen_random_uuid(), thumb, email, password)
         returning unqid;
      $BODY$
        LANGUAGE SQL
    
    Run Code Online (Sandbox Code Playgroud)