需要PostgreSQL中带in子句的表的输出
我试图通过代码传递循环或ID。我做了同样的事情来动态更新行,但是对于选择来说,我没有从DB获取值
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;
答案 0 :(得分:1)
不需要循环(或实际上是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 (...)
调整行以匹配选择列的数据类型。