使用 RETURNING 的函数调用时出现“列引用“id”不明确”错误

问题描述 投票:0回答:1

我的表有两个自动生成的列:

CREATE TABLE driver_orders (
  id SERIAL PRIMARY KEY,
  car_id INTEGER NOT NULL,
  location_from GEOGRAPHY  -- generated
    GENERATED ALWAYS AS
    (create_point_geography(start_point))
      stored,
  location_to GEOGRAPHY    -- generated
    GENERATED ALWAYS AS
    (create_point_geography(end_point))
      stored
);

我正在编写一个 postgres 函数,该函数插入一个新行,然后返回

id
location_from
location_to
。我正在关注这个问题

的答案

这是我想出的(删除了不相关的部分):

CREATE OR REPLACE FUNCTION create_driver_order(
    car_id INTEGER,
    s_point VARCHAR,
    e_point VARCHAR
  )
  RETURNS TABLE (
    id INTEGER, 
    location_from GEOGRAPHY, 
    location_to GEOGRAPHY
  )
    LANGUAGE plpgsql
AS $$
    DECLARE
    active_order_count INTEGER;
  BEGIN
    -- 1. count active orders
    --     ... omitted unrelated parts
    -- 2. check if active orders are less than two
    --     ... omitted unrelated parts

    -- 4. create order
    RETURN QUERY INSERT INTO driver_orders (
        car_id,
        start_point,
        end_point
      ) VALUES (
        car_id,
        s_point,
        e_point
      ) RETURNING id, location_from, location_to;
  END;
$$

函数创建成功。但当我调用它时:

select * from create_driver_order(
    889,
  '(5581326278118 29.220418907676738)'::VARCHAR,
  '(5581326274318 29.220548907676738)'::VARCHAR
)

我收到此错误:

列引用“id”不明确

有人能指出我做错了什么吗

sql postgresql plpgsql sql-function
1个回答
0
投票

使用

returns table
时,该输出表的列是在函数体的范围内定义的,因此您使用
returning id, location_from, location_to
可以引用输出记录的列,也可以引用要插入的表的列,或者甚至其他东西。只需明确指定您想要哪一个:

CREATE OR REPLACE FUNCTION create_driver_order(
    car_id INTEGER,
    s_point VARCHAR,
    e_point VARCHAR
  )
  RETURNS TABLE (
    id INTEGER, 
    location_from GEOGRAPHY, 
    location_to GEOGRAPHY
  )
    LANGUAGE plpgsql
AS $$
    DECLARE
    active_order_count INTEGER;
  BEGIN
    -- 1. count active orders
    --     ... omitted unrelated parts
    -- 2. check if active orders are less than two
    --     ... omitted unrelated parts

    -- 4. create order
    RETURN QUERY INSERT INTO driver_orders AS d (
        car_id,
        start_point,
        end_point
      ) VALUES (
        car_id,
        s_point,
        e_point
      ) RETURNING d.id, 
                  d.location_from, 
                  d.location_to;
  END $f$;
© www.soinside.com 2019 - 2024. All rights reserved.