You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PL/pgSQL插入行后返回全字段,解决返回record需列定义报错

问题原因

PostgreSQL 中返回泛型 record 类型的函数,数据库无法预先得知其返回的字段结构,因此调用时必须显式声明列定义列表,无法直接通过 SELECT * 方式调用。同时你原有代码还存在两个隐含问题:插入值硬编码未使用传入参数、ST_MakePoint 经纬度参数顺序写反、未显式返回结果。

修复方案

方案1:绑定表行类型(推荐)

由于你函数中 RETURNING * 返回的是 markers 表的整行数据,最简单的方式是将返回值类型修改为 markers 表的行类型:

create or replace function create_marker(title text, description text, latitude decimal, longitude decimal) 
-- 修改返回类型为markers表行类型
returns markers
language plpgsql
as $$
declare 
  res markers;
begin
  INSERT INTO markers (
    title,
    description,
    latitude,
    longitude,
    geometry
  ) VALUES 
  -- 替换硬编码值为传入参数,修正ST_MakePoint经纬度顺序(经度在前,纬度在后)
  (title, description, latitude, longitude, ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))
  RETURNING * into res;
  -- 显式返回结果
  return res;
end;
$$;

方案2:显式定义返回字段结构

如果不希望绑定表结构,可以用 RETURNS TABLE 显式指定返回的字段和对应类型,字段配置按你实际markers表结构调整即可:

create or replace function create_marker(title text, description text, latitude decimal, longitude decimal) 
returns table(
    id int,
    title text,
    description text,
    latitude decimal,
    longitude decimal,
    geometry geometry(Point,4326)
)
language plpgsql
as $$
begin
  return query
  INSERT INTO markers (
    title,
    description,
    latitude,
    longitude,
    geometry
  ) VALUES 
  (title, description, latitude, longitude, ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))
  RETURNING id, title, description, latitude, longitude, geometry;
end;
$$;

调用方式

修改完成后即可直接用你期望的方式调用:

SELECT * FROM create_marker('测试标记', '这是标记描述', 30.2672, 120.1551);

内容的提问来源于stack exchange,提问作者user1354934

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:15:01