PostgreSQL 列上的字符串格式约束不起作用

String Format Constraint On PostgreSQL Column Not Working

我正在将数据库从 SQL 服务器移动到 PostgreSQL,并在 table 之一的检查约束中遇到一些问题。 PostgreSQL 版本是 9.5.1.

我创建了一个 table,其中一列带有检查约束以强制执行格式。这在 SQL 服务器中有效。这个想法是,只能在其中一列中输入以字母 AF 开头并后跟三个数字字符(例如 AF001)的值。

SQL 创建 table 时看起来像这样:

CREATE TABLE TableName (
referenceID     VARCHAR(5) NOT NULL CHECK (referenceID LIKE 'AF[0-9][0-9][0-9]'),
comment         VARCHAR(50) NOT NULL,
PRIMARY KEY (referenceID)   
);

但是当我尝试输入任何数据时都失败了。数据输入示例:

INSERT INTO TableName (reference, comment) VALUES ('AF000','A comment');

我得到的错误是:

ERROR:  new row for relation "tablename" violates check constraint "tablename_referenceID_check"
DETAIL:  Failing row contains (AF000, A comment).

********** Error **********

ERROR: new row for relation "TableName" violates check constraint "tablename_referenceID_check"
SQL state: 23514
Detail: Failing row contains (AF000, A comment).

我假设问题出在实际的检查约束上,但我不确定。

LIKE 子句在 PostgreSQL 中不使用正则表达式模式。而不是 LIKE 你应该使用 SIMILAR TO 子句:

CREATE TABLE TableName (
referenceID     VARCHAR(5) NOT NULL CHECK (referenceID SIMILAR TO 'AF[0-9]{3}'),
comment         VARCHAR(50) NOT NULL,
PRIMARY KEY (referenceID)   
);