Sql 在存储过程中使用,postgres
我正在一张有物品清单的桌子上工作。每个项目都将有一个父项目。树结构也是如此 我需要获得项目的完整详细信息,如项目1>>项目1.1>>项目1.1.1>>项目1.1.1>>项目1.1.1.1,因此我决定创建一个函数,在项目1.1.1.1的示例id中,该函数将在传递项目id时返回详细信息Sql 在存储过程中使用,postgres,sql,postgresql,stored-procedures,common-table-expression,postgresql-8.4,Sql,Postgresql,Stored Procedures,Common Table Expression,Postgresql 8.4,我正在一张有物品清单的桌子上工作。每个项目都将有一个父项目。树结构也是如此 我需要获得项目的完整详细信息,如项目1>>项目1.1>>项目1.1.1>>项目1.1.1>>项目1.1.1.1,因此我决定创建一个函数,在项目1.1.1.1的示例id中,该函数将在传递项目id时返回详细信息 CREATE TABLE item ( item_id bigint, item_name text, item_code text, item_parentid bigint );
CREATE TABLE item (
item_id bigint,
item_name text,
item_code text,
item_parentid bigint
);
INSERT INTO item VALUES (1, 'Item 1', 'Item 1', NULL);
INSERT INTO item VALUES (2, 'Item 1.1', 'Item 1.1', 1);
INSERT INTO item VALUES (3, 'Item 1.1.1', 'Item 1.1.1', 2);
INSERT INTO item VALUES (4, 'Item 1.1.1.1', 'Item 1.1.1.1', 3);
INSERT INTO item VALUES (5, 'Item 1.1.1.1.1', 'Item 1.1.1.1.1', 4);
到目前为止,我必须使用“WITH RECURSIVE”编写一个查询来检索细节。但不知道如何在函数中写入相同的内容并返回项名称
WITH RECURSIVE itemtree (item_id, item_name, item_code,item_parentid,depth) AS (
SELECT item_id,item_name, item_code,item_parentid,1 FROM item WHERE item_id = 5
UNION
SELECT child.item_id,child.item_name, child.item_code,child.item_parentid,depth+1 FROM item child
INNER JOIN itemtree parent ON child.item_id = parent.item_parentid
)
SELECT array_to_string(array_agg(T.item_name), '>>>') FROM (SELECT * FROM itemtree ORDER BY depth DESC) T;
我正在使用PostgreSQL
8.4.22
您可以将查询写入插入格式,如下所示:
INSERT INTO item_names
SELECT name
FROM
(
WITH RECURSIVE itemtree (item_id, item_name, item_code,item_parentid,depth) AS (
SELECT item_id,item_name, item_code,item_parentid,1 FROM item WHERE item_id = 5
UNION
SELECT child.item_id,child.item_name, child.item_code,child.item_parentid,depth+1 FROM item child
INNER JOIN itemtree parent ON child.item_id = parent.item_parentid
)
SELECT array_to_string(array_agg(T.item_name), ' >>> ') AS name FROM (SELECT * FROM itemtree ORDER BY depth DESC) T
) res
解决办法相当简单。一开始,我的想法是使用SELECT-INTO
或execute
语句执行查询并返回结果。
但这完全没有必要。感谢另一个SO帖子。
现在我已经更正了这个问题,并将其发布在下面
--Have to add a new procedure to find the parent
CREATE OR REPLACE FUNCTION getitemname(itemid bigint) RETURNS text
LANGUAGE plpgsql STRICT
AS $$
DECLARE
item RECORD;
BEGIN
WITH RECURSIVE itemtree (item_id, item_name, item_code,item_parentid,depth) AS (
SELECT item_id,item_name, item_code,item_parentid,1 FROM om_item WHERE item_id = $1 AND deleted = 0
UNION
SELECT child.item_id,child.item_name, child.item_code,child.item_parentid,depth+1 FROM om_item child
INNER JOIN itemtree parent ON child.item_id = parent.item_parentid
)
SELECT array_to_string(array_agg(T.item_name), '>>>') INTO item FROM (SELECT * FROM itemtree ORDER BY depth DESC) T;
return item;
END;
$$;
SELECT getitemname(5);
看[这里][在开始时,特别是使用RETURN QUERY
@Houari,困难不在于返回结果。我只能找到SELECT INTO
关键字来执行查询并将结果存储到变量中。但我无法将上述查询写入SELECT INTO
格式。我如何执行此查询并返回函数的结果?虽然您的问题是关于插入到
,但现在看到了您的新答案,所以您的问题是如何在Postgres中执行函数