Aar*_*hen 2 database postgresql database-design
我在数据库中有一个字段,它是 XXXYYXXXX 形式的字符串,其中 X 是数字,Y 是字母 - 有没有办法定义表,以便尝试在该字段无法匹配的情况下插入新行一个错误?
如果我通过 ORM 处理数据库,我就会知道如何做到这一点,但不必在纯 SQL 中进行这样的验证。
create table my_table(
id serial primary key,
str text check (str ~ '^[a-zA-Z]{3}[0-9]{2}[a-zA-Z]{3}$')
);
insert into my_table values
(default, 'abc99def')
returning *;
id | str
----+----------
1 | abc99def
(1 row)
insert into my_table values
(default, '1bc99def')
returning *;
ERROR: new row for relation "my_table" violates check constraint "my_table_str_check"
DETAIL: Failing row contains (2, 1bc99def).
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |