【问题标题】:Sending array as parameter in postgresql在 postgresql 中发送数组作为参数
【发布时间】:2017-10-12 16:37:25
【问题描述】:

我正在尝试编写一个 postgresql 函数,该函数接受一个数组并返回用户没有属于该数组的 id。我写了这样的东西:

CREATE OR REPLACE FUNCTION user_api.get_user(banned_list TEXT[])
  RETURNS SETOF JSONB
AS $$
  SELECT to_jsonb(result)
  FROM (
    SELECT
           *
        FROM my_user.user_info
        WHERE my_user.user_info.user_id NOT IN (banned_list::TEXT[])

  ) AS result;
$$ LANGUAGE SQL SECURITY DEFINER;

但它会抛出这样的错误

ERROR:  operator does not exist text <> text[]
LINE 24: ...     WHERE my_user.user_info.user_id NOT IN (no...
                                                              ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我也试过用 CAST 函数,不行。

提前感谢您的帮助。

【问题讨论】:

    标签: sql database postgresql database-design


    【解决方案1】:

    您不能在数组上使用IN 运算符。你应该改用ALL()

        WHERE my_user.user_info.user_id <> ALL(banned_list)
    

    请注意,这只有在my_user.user_info.user_id 的类型是文本时才能正常工作。如果它是一个整数列,那么你应该使用一个整数数组作为参数:

    CREATE OR REPLACE FUNCTION user_api.get_user(banned_list int[])
      RETURNS SETOF JSONB
    AS $$
      SELECT to_jsonb(result)
      FROM (
        SELECT
               *
            FROM my_user.user_info
            WHERE my_user.user_info.user_id <> ALL(banned_list)
    
      ) AS result;
    $$ LANGUAGE SQL SECURITY DEFINER;
    

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 1970-01-01
      • 2014-06-16
      • 2021-03-30
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      相关资源
      最近更新 更多