【问题标题】:Set a check constraint for text array in Postgresql在 Postgresql 中为文本数组设置检查约束
【发布时间】:2016-08-02 10:58:26
【问题描述】:

我有一个名为 student 的表,id 和 name 作为 PostgreSQL 中的字段:

Create table student (id int, name text[]);

我需要为name 字段添加约束。这意味着它必须只接受该字段的字符。但是字段名是一个文本数组。

我试过这个检查约束:

Alter table student 
add constraint stud_const check (ALL(name) NOT LIKE '%[^a-zA-Z]%');

但是它会抛出这个错误:

ERROR:  syntax error atERROR:  syntax error at or near "all"
LINE 1: ... student add constraint stud_const check (all(name) ...
 or near "all"

我该如何解决这个问题? constraint 应设置为整个数组。

【问题讨论】:

  • 这个数组的目的是什么?学生应该有多个名字吗?
  • 是的,我会在里面存储名字和姓氏

标签: arrays regex postgresql constraints


【解决方案1】:

需要unnest数组才能匹配到regular expression:

select bool_and (n ~ '^[a-zA-Z]*$')
from unnest(array['John','Mary']) a(n)
;
 bool_and 
----------
 t

bool_and。由于无法在检查约束中使用子查询,因此将其包装在一个函数中:

create function check_text_array_regex (
    a text[], regex text
) returns boolean as $$

    select bool_and (n ~ regex)
    from unnest(a) s(n);

$$ language sql immutable;

并在检查约束中使用该函数:

create table student (
    id serial,
    name text[] check (check_text_array_regex (name, '^[a-zA-Z]*$'))
);

测试一下:

insert into student (name) values (array['John', 'Mary']);
INSERT 0 1

insert into student (name) values (array['John', 'Mary2']);
ERROR:  new row for relation "student" violates check constraint "student_name_check"
DETAIL:  Failing row contains (2, {John,Mary2}).

【讨论】:

    猜你喜欢
    • 2016-11-13
    • 2020-02-12
    • 2017-03-19
    • 2013-04-25
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多