[英]how to pass multiple variables to same parameter when calling postgresql function
i have total of 4 records in my table我的表中共有 4 条记录
id | url | name | description | last_update
----+------------------------------------+---------------------+-------------+-------------
1 | https://www.postgresqltutorial.com | PostgreSQL Tutorial | |
2 | http://www.oreilly.com | O'Reilly Media | |
3 | https://www.google.com | Google | | 2013-06-01
4 | http://www.postgresql.org | PostgreSQL | |
i have written a function to delete by passing name as a parameter, now i want to pass multiple names but i am facing error.我写了一个 function 通过传递名称作为参数来删除,现在我想传递多个名称但我面临错误。
CREATE OR REPLACE FUNCTION testing(first_name varchar(255))
RETURNS INTEGER AS
$BODY$
DECLARE emp_id INTEGER;
BEGIN
SELECT id into emp_id from links e where name = first_name;
DELETE FROM links WHERE id = emp_id;
return emp_id;
END
$BODY$
LANGUAGE plpgsql;
select * from testing('Google, PostgreSQL'); select * 来自测试('Google,PostgreSQL');
Error:- no function matches the given name and argument types.错误:- 没有 function 匹配给定的名称和参数类型。 you might need to add explicit type casts
您可能需要添加显式类型转换
Since you have a comma separated list, you can cast your parameter as an array with string_to_array function then apply the any operator.由于您有一个逗号分隔的列表,您可以使用string_to_array function将参数转换为数组,然后应用any运算符。 Further there is no reason for pgplsql, this can be written in a single sql statement, then wrapped it into a sql parameter/function.
此外,没有理由使用 pgplsql,这可以写在单个 sql 语句中,然后将其包装到 sql 参数/函数中。 (see demo )
(见演示)
create or replace procedure testing(first_names varchar(255))
language sql
as $$
delete from links
where name = any(string_to_array(first_names, ','));
$$;
If you want to pass several values, you have to define the function to accept several values.如果要传递多个值,则必须定义 function 以接受多个值。 There are two ways:
有两种方式:
a variadic function:可变参数 function:
CREATE FUNCTION testing(VARIADIC first_name text[])...
This is called like这叫做像
SELECT testing('arg1', 'arg2', 'arg3');
a function that accepts an array as parameter:接受数组作为参数的 function:
CREATE FUNCTION testing(first_name text[])...
This is called like这叫做像
SELECT testing(ARRAY['arg1', 'arg2', 'arg3']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.