错误:查询的结构与函数结果类型不匹配

时间:2018-07-21 07:55:39

标签: mysql postgresql stored-procedures stored-functions

我正在尝试将mySQL存储过程转换为postgrSQL存储函数。我是PostgreSQL的新手。第一次尝试将join Store过程转换为store函数。但我收到以下错误消息

ERROR:  structure of query does not match function result type
DETAIL:  Returned type text does not match expected type character varying in column 3.
CONTEXT:  PL/pgSQL function getsummarypagecontentsurveyform(numeric) line 3 at RETURN QUERY 

存储过程

CREATE PROCEDURE [dbo].[GetSummaryPageContentSurveyForm]     
    @nRoomAllocationID bigint
AS
BEGIN
   SELECT  Employee.sEmpName, RoomInvestigatorMapping.sComment,
           Employee.sEmpName + ' : ' + RoomInvestigatorMapping.sComment as CommentsToDisplay
   FROM    RoomInvestigatorMapping INNER JOIN Employee 
        ON RoomInvestigatorMapping.nInvestigatorID = Employee.nEmpID
   Where    RoomInvestigatorMapping.nRoomAllocationID = @nRoomAllocationID 
END   
GO

存储功能

CREATE OR REPLACE FUNCTION GetSummaryPageContentSurveyForm (        
    p_nroom_allocation_id numeric)

    RETURNS Table(res_semp_name character varying,res_scomment character varying,
                  res_comments_to_display character varying)
AS $$
BEGIN
 Return Query    
   SELECT  employee.semp_name, roominvestigatormapping.scomment,
           employee.semp_name || ' : ' || roominvestigatormapping.scomment as comments_to_display
   FROM    roominvestigatormapping INNER JOIN employee 
           ON roominvestigatormapping.ninvestigator_id = employee.nemp_id
   Where   roominvestigatormapping.nroom_allocation_id = p_nroom_allocation_id; 
END;

$$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:1)

PostgreSQL函数必须具有定义的结果类型。运行时检查输出是否与定义的类型相同。在您的情况下,第三个表达式返回文本而不是varchar。您需要将该表达式显式转换为varchar:

$$
BEGIN
  RETURN QUERY    
    SELECT  employee.semp_name, roominvestigatormapping.scomment,
         (employee.semp_name || ' : ' || roominvestigatormapping.scomment)::varchar as comments_to_display
      FROM    roominvestigatormapping INNER JOIN employee 
        ON roominvestigatormapping.ninvestigator_id = employee.nemp_id
     WHERE   roominvestigatormapping.nroom_allocation_id = p_nroom_allocation_id; 
END;
$$

我使用了强制转换运算符::

somevalue::varchar