问题描述
这是我的表格
我在表格中插入多于一行的函数
CREATE TABLE mahasiswa
(
nim CHAR(10),
nama VACHAR(40)
CONSTRAINT pk_nim PRIMARY KEY(nim)
)
;
这是我创建的函数
<$ $($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' ;
$$
LANGUAGE'sql';
当我调用这个函数时
SELECT insertdata('1234567890','Nahrun'),
('0987654321','Hartono');
只插入一行。
如何修改我的函数来一次插入多行?
($) 不要引用语言名称。这是一个标识符。
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$ $ $' AS
$$
插入到mahasiswa(col_name1,col_name2)
VALUES($ 1,$ 2);
$$
LANGUAGE sql STRICT;
char(n) code>,除非你知道你在做什么。我只是使用
text
。
>插入多行,您可以使用相同数量的元素组合一个复合类型数组或两个数组并行并行。演示后者:
pre $ $ codeREATE FUNCTION insertdata(_arr1 text [],_arr2 text [])
RETURNS VOID AS
$$
INSERT INTO mahasiswa(col_name1,col_name2)
SELECT unnest(_arr1),unnest(_arr2);
$$
LANGUAGE sql STRICT;
通话:
SELECT insertdata('{1234567890,0987654321}','{Nahrun,Hartono}');
我宁愿使用plpgsql函数,检查两个数组中元素的数目是否相同防止错误。使用 array_length(arr1,1)
...
Postgres 9.4或更高版本...
...引入了unnest的一个新变体,它并行接受多个数组 - 没有上述hack的怪癖(从不默认为 and this is the function I created When I call the function like this only one row is inserted. How can I modify my function to insert more than one row at a time? The function you have should rather be: Don't quote the language name. It's an identifier. Always provide a target list with persisted statements. Else, if you later change the table definition, the function can behave in unexpected ways. Never use To insert multiple rows, you can take an array of composite type or two arrays with the same number of elements to unnest in parallel. Demonstrating the latter: Call: I would rather use a plpgsql function and check that the number of elements is the same in both arrays to prevent mistakes. Use ... introduced a new variant of unnest that accepts multiple arrays in parallel - without the quirks of the above hack (never defaults to a 这篇关于如何在PostgreSQL中使用函数插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! CROSS JOIN $ c
$ b $ pre $ INSERT INTO mahasiswa(col_name1,col_name2)
SELECT * FROM unnest(_arr1,_arr2); - 必须在FROM列表中
CREATE TABLE mahasiswa
(
nim CHAR(10),
nama VACHAR(40)
CONSTRAINT pk_nim PRIMARY KEY (nim)
)
;
CREATE FUNCTION insertdata(CHAR(10),varchar(40))
RETURNS VOID AS
$$
INSERT INTO mahasiswa VALUES ($1,$2);
$$
LANGUAGE 'sql';
SELECT insertdata ('1234567890','Nahrun'),
('0987654321','Hartono');
CREATE FUNCTION insertdata(varchar(10),varchar(40))
RETURNS VOID AS
$$
INSERT INTO mahasiswa(col_name1, col_name2)
VALUES ($1,$2);
$$
LANGUAGE sql STRICT;
char(n)
, unless you know what you are doing. I'd just use text
.CREATE FUNCTION insertdata(_arr1 text[], _arr2 text[])
RETURNS VOID AS
$$
INSERT INTO mahasiswa(col_name1, col_name2)
SELECT unnest(_arr1), unnest(_arr2);
$$
LANGUAGE sql STRICT;
SELECT insertdata ('{1234567890,0987654321}', '{Nahrun,Hartono}');
array_length(arr1, 1)
...Postgres 9.4 or later ...
CROSS JOIN
) INSERT INTO mahasiswa(col_name1, col_name2)
SELECT * FROM unnest(_arr1, _arr2); -- must be in FROM list