我有下表:
create table telephones(
client_id char(9) not null CHECK (cif_cliente SIMILAR TO '[0-9]{8}[A-Z]'),
telephone_number char(14)
);
我想限制該telephone_number欄位,以便我只能輸入諸如 (123)-45-67-89 或 (666)-22-33-55 之類的值,其中開頭的括號中始終有 3 個數字,后跟連字符, 2 個帶另一個連字符的數字,2 個帶另一個連字符的數字和 2 個末尾的數字。
我試過了,但是當我嘗試插入正確的數字時,我不能:
create table telephones(
client_id char(9) not null CHECK (cif_cliente SIMILAR TO '[0-9]{8}[A-Z]'),
telephone_number char(14) CHECK telephone_number SIMILAR TO '([0-9]{3})-[0-9]{2}-[0-9]{2}-[0-9]{2}'),
);
insert into telephones values('12345678K', '(666)-22-33-55');
知道如何解決這個問題嗎?
uj5u.com熱心網友回復:
作為個人喜好,我不使用SIMILAR TO由 SQL 語言定義的。
我從簡單的LIKE(對大多數情況下有用)跳到匹配格式良好的模式的正則運算式模式。我沒有找到好的用例SIMILAR TO,但這只是我。
你可以做:
create table telephones (
client_id char(9) not null CHECK (client_id ~ '[0-9]{8}[A-Z]'),
telephone_number char(14) check (telephone_number ~
'\(\d{3}\)\-\d{2}\-\d{2}\-\d{2}'
)
);
insert into telephones (client_id, telephone_number)
values ('12345678A', '(122)-45-67-89'); -- succeeds
insert into telephones (client_id, telephone_number)
values ('12345678A', '122-45-67-89'); -- fails
insert into telephones (client_id, telephone_number)
values ('12345678A', '(122)-45-6-89'); -- fails
請參閱db<>fiddle的運行示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519445.html
