PostgreSQL中的数组

8nuwlpux  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(2)|浏览(148)

我尝试对ent_id数组执行3个操作(2个删除和1个更新)。这个数组是在我的脚本中的select中构建的。

CREATE OR REPLACE FUNCTION run_script()
  RETURNS VOID
AS $$
DECLARE
  all_ent bigint[];
BEGIN
  SELECT ent_id INTO all_ent FROM entretiens ent WHERE ent.ent_statut = 'T';

  RAISE INFO 'Start';

  DELETE FROM documents WHERE ent_id IN (all_ent);

  DELETE FROM comite WHERE ent_id IN (all_ent);

  DELETE entretiens ent SET ent_statut = 'N' WHERE ent_id IN (all_ent);

  RAISE INFO 'End';
END;
$$ LANGUAGE plpgsql;

SELECT run_script();

字符串
当我运行脚本时,我遇到了这个错误:

ERROR: malformed array literal: "535030"
Détail : Array value must start with "{" or dimension information.


有什么建议吗?

xtfmy6hx

xtfmy6hx1#

你可以用下面的方法创建和使用数组。* 数组的值来自[1],但不是来自[0],所以[0]返回NULL;the doc详细解释了它:

SELECT '{1,2,3,4,5}'::INTEGER[]; -- {1,2,3,4,5}
SELECT ('{1,2,3,4,5}'::INTEGER[])[2]; -- 2
SELECT ('{1,2,3,4,5}'::INTEGER[])[0]; -- NULL;
SELECT ('{1,2,3,4,5}'::INTEGER[])[2:4]; -- {2,3,4}
SELECT ('{1,2,3,4,5}'::INTEGER[])[:4]; -- {1,2,3,4}
SELECT ('{1,2,3,4,5}'::INTEGER[])[2:]; -- {2,3,4,5}
SELECT ('{1,2,3,4,5}'::INTEGER[])[:]; -- {1,2,3,4,5}

字符串
或者:

SELECT ARRAY[1,2,3,4,5]::INTEGER[]; -- {1,2,3,4,5}
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[2]; -- 2
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[0]; -- NULL;
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[2:4]; -- {2,3,4}
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[:4]; -- {1,2,3,4}
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[2:]; -- {2,3,4,5}
SELECT (ARRAY[1,2,3,4,5]::INTEGER[])[:]; -- {1,2,3,4,5}


或者. * 如果省略INTEGER[],下面的数组是TEXT[]类型,不能进行计算,并且不要在string_to_array()的第一个参数中放置任何空格,否则由,分隔的值有空格:

SELECT string_to_array('1,2,3,4,5', ',')::INTEGER[]; -- {1,2,3,4,5}
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[2]; -- 2
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[0]; -- NULL;
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[2:4]; -- {2,3,4}
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[:4]; -- {1,2,3,4}
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[2:]; -- {2,3,4,5}
SELECT (string_to_array('1,2,3,4,5', ',')::INTEGER[])[:]; -- {1,2,3,4,5}

9q78igpj

9q78igpj2#

设置为数组选定字段值:

select ARRAY(
    select ent_id
    from entretiens ent
    where ent.ent_statut = 'T'
) into all_ent;

字符串
在查询中使用数组:

delete
from documents
where ent_id in (select aaa from unnest(all_ent) tb(aaa));

相关问题