在带有声明变量列表的子句中 PostgreSQL
In clause with a list of declared variables PostgreSQL
我有这个:
CREATE or REPLACE FUNCTION name_list(name_of_interest text)
RETURNS table (name text,
sex text,
age int,
state text)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN query
SELECT name, sex, age, state FROM employee
INNER JOIN address_book ON employee.id = address_book.id
WHERE name = name_of_interest;
然后运行函数通过判断name_of_interest
,像这样:
SELECT * FROM name_list('Harry Potter');
如果我只对一个名字感兴趣,这很好用,但是如果我想将 name_of_interest
替换为名称列表,即 ('Harry Potter', 'Brad Pitt', 'Stephen Curry')
并将 WHERE
子句更改为 WHERE name in (name_of_interest)
,则此功能不再起作用。
如有任何意见或想法,我们将不胜感激!
您使用数组格式并发送到查询:
CREATE or REPLACE FUNCTION name_list(name_of_interest text[])
RETURNS table (name text,
sex text,
age int,
state text)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN query
SELECT name, sex, age, state FROM employee
INNER JOIN address_book ON employee.id = address_book.id
WHERE name = any(name_of_interest);
END;
$$;
然后运行查询如下:
SELECT * FROM name_list(array['Harry Potter', 'Brad Pitt', 'Stephen Curry']::text[]);
我有这个:
CREATE or REPLACE FUNCTION name_list(name_of_interest text)
RETURNS table (name text,
sex text,
age int,
state text)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN query
SELECT name, sex, age, state FROM employee
INNER JOIN address_book ON employee.id = address_book.id
WHERE name = name_of_interest;
然后运行函数通过判断name_of_interest
,像这样:
SELECT * FROM name_list('Harry Potter');
如果我只对一个名字感兴趣,这很好用,但是如果我想将 name_of_interest
替换为名称列表,即 ('Harry Potter', 'Brad Pitt', 'Stephen Curry')
并将 WHERE
子句更改为 WHERE name in (name_of_interest)
,则此功能不再起作用。
如有任何意见或想法,我们将不胜感激!
您使用数组格式并发送到查询:
CREATE or REPLACE FUNCTION name_list(name_of_interest text[])
RETURNS table (name text,
sex text,
age int,
state text)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN query
SELECT name, sex, age, state FROM employee
INNER JOIN address_book ON employee.id = address_book.id
WHERE name = any(name_of_interest);
END;
$$;
然后运行查询如下:
SELECT * FROM name_list(array['Harry Potter', 'Brad Pitt', 'Stephen Curry']::text[]);