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

44u64gxh  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(208)

我有这个表,其中有两个自动生成的列:

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函数,它插入一个新行,然后返回idlocation_fromlocation_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”不明确
有人能指出我做错了什么吗?

nzrxty8p

nzrxty8p1#

当使用returns table时,输出表的列是在函数体的作用域中定义的,所以returning id, location_from, location_to的使用可以引用输出记录的列,也可以引用要插入的表的列,甚至可以引用其他内容。只需显式指定所需的列即可。Demo

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 $f$
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$;

字符串

相关问题