gpt4 book ai didi

postgresql - 在 postgres 中的子句

转载 作者:行者123 更新时间:2023-11-29 13:11:22 26 4
gpt4 key购买 nike

在 PostgreSQL 中需要带有 in 子句的表的输出

我试图从我的代码中创建循环或 ID。我做了同样的事情来动态更新行,但是对于选择我没有从数据库中获取值

CREATE OR REPLACE FUNCTION dashboard.rspgetpendingdispatchbyaccountgroupidandbranchid(
IN accountgroupIdCol numeric(8,0),
IN branchidcol character varying
)
RETURNS void
AS
$$
DECLARE
ArrayText text[];
i int;
BEGIN
select string_to_array(branchidcol, ',') into ArrayText;
i := 1;
loop
if i > array_upper(ArrayText, 1) then
exit;
else
SELECT
pd.branchid,pd.totallr,pd.totalarticle,pd.totalweight,
pd.totalamount
FROM dashboard.pendingdispatch AS pd
WHERE
pd.accountgroupid = accountgroupIdCol AND pd.branchid IN(ArrayText[i]::numeric);
i := i + 1;
end if;
END LOOP;
END;
$$ LANGUAGE 'plpgsql' VOLATILE;

最佳答案

不需要循环(实际上是 PL/pgSQL)

你可以直接在查询中使用数组,例如:

where pd.branchid = any (string_to_array(branchidcol, ','));

但是你的函数没有返回任何东西,所以显然你不会得到结果。

如果您想返回该 SELECT 查询的结果,您需要将函数定义为 returns table (...) 然后使用 return query - 或者更好的做法是让它成为一个 SQL 函数:

CREATE OR REPLACE FUNCTION dashboard.rspgetpendingdispatchbyaccountgroupidandbranchid(
IN accountgroupIdCol numeric(8,0),
IN branchidcol character varying )
RETURNS table(branchid integer, totallr integer, totalarticle integer, totalweight numeric, totalamount integer)
AS
$$
SELECT pd.branchid,pd.totallr,pd.totalarticle,pd.totalweight, pd.totalamount
FROM dashboard.pendingdispatch AS pd
WHERE pd.accountgroupid = accountgroupIdCol
AND pd.branchid = any (string_to_array(branchidcol, ',')::numeric[]);
$$
LANGUAGE sql
VOLATILE;

请注意,我根据名称猜测了查询列的数据类型。您必须调整带有 returns table (...) 的行以匹配选择列的数据类型。

关于postgresql - 在 postgres 中的子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54220356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com