Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 为Postgresql中的文本数组设置检查约束_Arrays_Regex_Postgresql_Constraints - Fatal编程技术网

Arrays 为Postgresql中的文本数组设置检查约束

Arrays 为Postgresql中的文本数组设置检查约束,arrays,regex,postgresql,constraints,Arrays,Regex,Postgresql,Constraints,我有一个名为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]%'); create table stu

我有一个名为
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]%');
create table student (
    id serial,
    name text[] check (check_text_array_regex (name, '^[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"
我怎样才能解决这个问题?
约束
应设置为整个数组

有必要将数组与一个:

。由于无法在检查约束中使用子查询,请将其包装到函数中:

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;
并使用检查约束中的函数:

Alter table student 
add constraint stud_const check (ALL(name) NOT LIKE '%[^a-zA-Z]%');
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}).

此阵列的用途是什么?一个学生应该有不止一个名字吗?是的,我会把名字和姓氏储存在里面