微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – Postgres存储函数如何返回一个表

我想知道一个Postgres存储函数如何返回一个表,具有标识列.我使用返回setof returnType:
-- create employeeSearchResult returnType
create type employeeAllReturnType as
(
  id bigserial,"positionId" integer,"subjectId" bigint,"dateEngaged" date,"nextKin" text,"nrcNo" text,dob date,father text,mother text,wife text,"userId" integer,"statusId" integer,"mainCode" text,"subCode" text
);


-- Search for emmployee by name
CREATE OR REPLACE FUNCTION "employee_search_by_name"(employeeNameIN text)
returns setof employeeAllReturnType as 
$$
declare
    results record;
    resultsRow employee%rowtype;
    nameIn text;
begin
    nameIn = employeeNameIN || '%';
    for results in select 
        employee.id,-- bigserial NOT NULL,employee."positionId",-- integer,employee."subjectId",-- bigint NOT NULL,employee."dateEngaged",-- date,employee."nextKin",-- text,employee."nrcNo",employee.dob,employee.father,employee.mother,employee.wife,employee."userId",-- integer NOT NULL,employee."statusId",employee."mainCode",-- character(5) NOT NULL,employee."subCode"-- character(10),from employee,subject where employee."subjectId" = subject.id and (subject.name1 ILIKE nameIn OR subject.name2 ILIKE nameIn OR subject.name3 ILIKE nameIn OR subject.name4 ILIKE nameIn) loop
      return next results;
    end loop;
end;
$$language 'plpgsql';

并返回table():

-- Search for emmployee by name
CREATE OR REPLACE FUNCTION "employee_search_by_name"(employeeNameIN text)
returns table (id bigserial,position integer,subject bigint,date_engaged date,next_kin text,nrc_no text,user_id integer,status_id integer,main_code text,sub_code text) as 
$$
declare
    results record;
    resultsRow employee%rowtype;
    nameIn text;
begin
    nameIn = employeeNameIN || '%';
    for results in select 
        employee.id,subject where employee."subjectId" = subject.id and (subject.name1 ILIKE nameIn OR subject.name2 ILIKE nameIn OR subject.name3 ILIKE nameIn OR subject.name4 ILIKE nameIn) loop
      return next results;
    end loop;
end;
$$language 'plpgsql';

但都有以下格式的输出

"(1,1,2011-12-01,Timea,fg1254,1981-12-27,moses,Sarada,timea,"ADM  ","1         ")"
"(37,3,10,2011-11-11,s,"OP   ","1         ")"

有没有我可以输出如表的选择结果的输出

"1";1;1;"2011-12-01";"Timea";"fg1254";"1981-12-27";"moses";"Sarada";"timea";1;1;"ADM  ";"1         "

这样从前端处理结果数据就不需要一个解析器.

你应该像这样查询你的函数
SELECT * FROM employee_search_by_name('Bob');

另外,为了简化您的功能,您可以查看RETURN QUERY EXECUTE ...的结构.并且不需要引用plpgsql关键字.

原文地址:https://www.jb51.cc/postgresql/191710.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐