PostgreSQL函数选择*

Mar*_*kus 2 postgresql stored-procedures

如何在postgres中的函数中使用select*from some_table?

Luc*_*c M 6

CREATE OR REPLACE FUNCTION  my_function() RETURNS INTEGER AS '
   DECLARE
      your_record your_table%ROWTYPE;
   BEGIN

      FOR your_record IN SELECT * FROM your_table  
      LOOP

      --
      -- You can access fields of your table using .
      --    your_record.your_field
        ...
      END LOOP;


   END;
' LANGUAGE 'plpgsql'
STABLE;
Run Code Online (Sandbox Code Playgroud)

要么

CREATE OR REPLACE FUNCTION  my_function() RETURNS INTEGER AS '
   DECLARE
      your_record your_table%ROWTYPE;
   BEGIN

      SELECT * INTO your_record FROM your_table;

      --
      -- You can access fields of your table using .
      --    your_record.your_field

   END;
' LANGUAGE 'plpgsql'
STABLE;
Run Code Online (Sandbox Code Playgroud)


编辑:

随着join返回记录:

CREATE OR REPLACE FUNCTION  my_function() RETURNS SETOF record AS '
   DECLARE
      your_record record;
   BEGIN
      --
      -- You should specify a list of fields instead of *
      --
      FOR your_record IN SELECT * FROM your_table INNER JOIN ...           
         RETURN NEXT your_record;
      END LOOP;
   END;
' LANGUAGE 'plpgsql'
STABLE;
Run Code Online (Sandbox Code Playgroud)

要使用my_function(),您必须指定字段和数据类型: 请参阅此处的详细信息