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

前端之家收集整理的这篇文章主要介绍了postgresql – Postgres存储函数如何返回一个表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道一个Postgres存储函数如何返回一个表,具有标识列.我使用返回setof returnType:
  1. -- create employeeSearchResult returnType
  2. create type employeeAllReturnType as
  3. (
  4. 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
  5. );
  6.  
  7.  
  8. -- Search for emmployee by name
  9. CREATE OR REPLACE FUNCTION "employee_search_by_name"(employeeNameIN text)
  10. returns setof employeeAllReturnType as
  11. $$
  12. declare
  13. results record;
  14. resultsRow employee%rowtype;
  15. nameIn text;
  16. begin
  17. nameIn = employeeNameIN || '%';
  18. for results in select
  19. 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
  20. return next results;
  21. end loop;
  22. end;
  23. $$language 'plpgsql';

并返回table():

  1. -- Search for emmployee by name
  2. CREATE OR REPLACE FUNCTION "employee_search_by_name"(employeeNameIN text)
  3. 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
  4. $$
  5. declare
  6. results record;
  7. resultsRow employee%rowtype;
  8. nameIn text;
  9. begin
  10. nameIn = employeeNameIN || '%';
  11. for results in select
  12. 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
  13. return next results;
  14. end loop;
  15. end;
  16. $$language 'plpgsql';

但都有以下格式的输出

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

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

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

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

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

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

猜你在找的Postgre SQL相关文章