PostgreSQL新手创建返回查询结果的函数遇语法错误,求排查
PostgreSQL函数创建错误修正
你的代码存在三个关键问题:
returns table语法错误:PostgreSQL要求声明返回表时,必须明确指定列名和对应的数据类型,不能仅写table。- PL/pgSQL函数内执行查询需要用
RETURN QUERY:直接写SELECT语句无法返回结果,必须用该关键字将查询结果返回。 - 缺少函数语言声明:需要指定函数使用的语言(如
plpgsql或sql)。
修正后的PL/pgSQL版本
create function getdevices() returns table( DeviceID int, -- 请根据实际表结构替换为对应的数据类型 SerialNumber text, ProductCode text, Description text, SoftwareVersion text, Build text, BuildDate date, Assigned boolean, GroupID int, DeviceConnectionIndex int ) as $$ begin RETURN QUERY SELECT DeviceID, SerialNumber, ProductCode, Description, SoftwareVersion, Build, BuildDate, Assigned, GroupID, DeviceConnectionIndex FROM dbo.Device; end; $$ language plpgsql;
更简洁的SQL函数版本
如果只是简单返回查询结果,用SQL函数更高效:
create function getdevices() returns table( DeviceID int, SerialNumber text, ProductCode text, Description text, SoftwareVersion text, Build text, BuildDate date, Assigned boolean, GroupID int, DeviceConnectionIndex int ) as $$ SELECT DeviceID, SerialNumber, ProductCode, Description, SoftwareVersion, Build, BuildDate, Assigned, GroupID, DeviceConnectionIndex FROM dbo.Device; $$ language sql;
注意:请根据dbo.Device表中各列的实际数据类型替换示例中的类型(比如int、text等)。
内容的提问来源于stack exchange,提问作者ChrisAsi71
相关产品推荐
相关产品推荐

