gpt4 book ai didi

sql - 在使用数组作为参数的函数中传递超过 100 个参数

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

我需要创建一个存储过程来检查表中是否存在特定帐户(如果存在)

需要在 PostgreSQL 中创建自定义函数来更新/插入表。我需要传递大约 200 个无法实现的值。有人建议使用数组作为参数。但它不适合我。所有 200 个字段都与 int、varchar、double、float 等组合在一起。而且我们不能更改顺序。

请告诉我如何将这些作为参数传递并在更新/插入语句中使用它们。

我的代码看起来像这样

create or replace function test(variadic text[])
....
Begin
Insert into customers (custno , company, firstname) values ($1[1],$1[2],$1[3]);
....
END;

最佳答案

最好的方法是将复合类型作为参数传递。

您可以使用像表一样命名并通过 CREATE TABLE 自动创建的类型。

这是一个包含 300 列的工作示例:

CREATE TABLE wide (
i0 integer,
t0 text,
d0 date,
i1 integer,
t1 text,
d1 date,
i2 integer,
t2 text,
d2 date,
i3 integer,
t3 text,
d3 date,
[... many missing columns]
i99 integer,
t99 text,
d99 date
);

CREATE OR REPLACE PROCEDURE insert_wide(arg wide)
LANGUAGE plpgsql AS
$$BEGIN
INSERT INTO wide SELECT (arg).*;
END;$$;

CALL insert_wide(
ROW(
0,
'atext',
current_date + 0,
1,
'atext',
current_date + 1,
2,
'atext',
current_date + 2,
3,
'atext',
current_date + 3,
[again, many missing columns]
99,
'atext',
current_date + 99
)
);

但我认为,如果您的表格包含那么多列,那您就做错了。

关于sql - 在使用数组作为参数的函数中传递超过 100 个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58104534/

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