如何在 plpgsql 中编辑和 return 游标?
How to edit and return a Cursor in plpgsql?
我正在函数内部做一个简单的查询,我需要更改这个查询的值,但仅供参考。我不需要像这样更新 table 。我设法编辑了值,但我不知道如何return它们。
CREATE OR REPLACE FUNCTION setDetails(INTEGER,INTEGER) RETURNS TABLE (
id INTEGER,
name TEXT,
subsidy TEXT,
stratum_id NUMERIC,
price TEXT,
total FLOAT
) AS $$
DECLARE
service Record;
subscibed_services Record;
BEGIN
for service in SELECT services.*, false as subscribed, (CAST(services.price AS float) - CAST(services.subsidy AS float)) AS total FROM services WHERE services.stratum_id = loop
for subscibed_services in SELECT services.id FROM services WHERE id IN (SELECT DISTINCT charge_details.service_id FROM charge_details WHERE charge_details.charge_id = ) loop
if (CAST(subscibed_services.id as INTEGER) = CAST(service.id as INTEGER)) then
service.subscribed := true;
EXIT;
else
service.total := 0;
end if;
end loop;
end loop;
END;
$$ LANGUAGE plpgsql;
下面这个函数会被执行
SELECT setDetails(2,6320)
As you can see, the query does not bring me anything.
非常感谢您的帮助,对于使用 google 翻译器表示歉意:D
如果你想要table函数的一些结果,你应该填充相关的变量(在table
子句列表中定义),然后你应该使用RETURN NEXT
语句。 documentation.
对此进行了很好的描述
简单示例:
CREATE OR REPLACE FUNCTION foo(n int)
RETURNS TABLE(a int, b int)
AS $$
BEGIN
FOR i IN 1 .. n
LOOP
a := i; b := i + 1;
RETURN NEXT;
END LOOP;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM foo(10);
您的代码还有另一个性能错误。查询的两个嵌套循环可能很慢。您可以使用 JOIN
(在本例中为自连接),并迭代一个循环而不是嵌套两个循环。
我正在函数内部做一个简单的查询,我需要更改这个查询的值,但仅供参考。我不需要像这样更新 table 。我设法编辑了值,但我不知道如何return它们。
CREATE OR REPLACE FUNCTION setDetails(INTEGER,INTEGER) RETURNS TABLE (
id INTEGER,
name TEXT,
subsidy TEXT,
stratum_id NUMERIC,
price TEXT,
total FLOAT
) AS $$
DECLARE
service Record;
subscibed_services Record;
BEGIN
for service in SELECT services.*, false as subscribed, (CAST(services.price AS float) - CAST(services.subsidy AS float)) AS total FROM services WHERE services.stratum_id = loop
for subscibed_services in SELECT services.id FROM services WHERE id IN (SELECT DISTINCT charge_details.service_id FROM charge_details WHERE charge_details.charge_id = ) loop
if (CAST(subscibed_services.id as INTEGER) = CAST(service.id as INTEGER)) then
service.subscribed := true;
EXIT;
else
service.total := 0;
end if;
end loop;
end loop;
END;
$$ LANGUAGE plpgsql;
下面这个函数会被执行
SELECT setDetails(2,6320)
As you can see, the query does not bring me anything.
非常感谢您的帮助,对于使用 google 翻译器表示歉意:D
如果你想要table函数的一些结果,你应该填充相关的变量(在table
子句列表中定义),然后你应该使用RETURN NEXT
语句。 documentation.
简单示例:
CREATE OR REPLACE FUNCTION foo(n int)
RETURNS TABLE(a int, b int)
AS $$
BEGIN
FOR i IN 1 .. n
LOOP
a := i; b := i + 1;
RETURN NEXT;
END LOOP;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM foo(10);
您的代码还有另一个性能错误。查询的两个嵌套循环可能很慢。您可以使用 JOIN
(在本例中为自连接),并迭代一个循环而不是嵌套两个循环。