首页 > 解决方案 > 如何将字符串数组传递给函数并在 SQL 的“IN”语句中使用它

问题描述

这可能很简单,但不知何故,我仍然不正确。如何将字符串数组传递给函数并在 SQL 的“IN”语句中使用它

CREATE OR REPLACE function test_function(array_para text)
RETURNS TABLE (data text) 
AS $$
begin
    
    return query select col1 from my_table where my_table.col2 in(array_para)
END 
$$ 
LANGUAGE 'plpgsql';

我怎么称呼它?也许 -

select test_function('''ABC'', ''MITT''')

标签: functionpostgresql-9.5

解决方案


您需要将参数声明为和数组,例如text[]. 您也不需要 PL/pgSQL:

CREATE OR REPLACE function test_function(array_para text[])
RETURNS TABLE (data text) 
AS $$
  select col1 
  from my_table 
  where my_table.col2 = any (array_para)
$$ 
LANGUAGE sql;

然后调用它:

select *
from test_function(array['ABC', 'MITT']);

另一种选择是使用variadic参数:

CREATE OR REPLACE function test_function(variadic array_para text[])
RETURNS TABLE (data text) 
AS $$
  select col1 
  from my_table 
  where my_table.col2 = any (array_para)
$$ 
LANGUAGE sql;

然后你可以调用它:

select *
from test_function('ABC', 'MITT', 'DEF');

推荐阅读