检查数据是否有默认长度并且它是 sql 中的数字

Check if data has a default length and it's numeric in sql

在我的 table 中,我有一列是 6 位代码。

myCode CHAR(6) PRIMARY KEY CHECK ( SUBSTRING ( myCode ,1 ,1) >='0' AND
SUBSTRING ( myCode ,1 ,1) <= '9' AND ...#for all positions

还有比这个更快的方法吗?

使用正则表达式:

CREATE TABLE tabq(myCode CHAR(6) PRIMARY KEY CHECK (myCode ~'^([0-9]{6})$') );

如果您只想识别匹配此模式的记录,您可以尝试:

SELECT *
FROM tabq
WHERE myCode !~ '^\d{6}$';

Rextester Demo

更简单:

mycode ~ '\d{6}'

\d is the class shorthand for digits.
不要用另一个\转义\,除非你是运行早已过时的standard_conforming_strings = off。参见:

  • Insert text with single quotes in PostgreSQL

不需要括号。
在使用 char(6) 时,您甚至不需要 ^$ 来锚定表达式的开始和结束(即使这不会造成伤害)。数据类型不完全是废话的罕见用例。参见:

  • Best way to check for "empty or null value"
  • Any downsides of using data type "text" for storing strings?

较短的字符串用空格填充,不通过 CHECK 约束。
较长的字符串不通过 char(6).
类型的长度规范 (但要小心!像 '1234567'::char(6) 这样的 显式 强制转换会静默截断。)

CREATE TABLE tbl (mycode char(6) PRIMARY KEY CHECK (mycode ~ '\d{6}'));

我仍然建议不要使用过时的类型 char(6)。极端情况下的奇怪行为。请改用 text。那么你实际上需要 ^$ 在正则表达式中:

CREATE TABLE tbl (mycode text PRIMARY KEY CHECK (mycode ~ '^\d{6}$'));

dbfiddle here


您发表评论(真是新问题):

and what about that digits inside has to be distinct?

在字符串中强制使用唯一数字并不那么简单。如果您安装了 additional module intarray,则有一个优雅的解决方案 sort()uniq():

CREATE TEMP TABLE tbl3 (
   mycode varchar(6) PRIMARY KEY
 , CONSTRAINT chk_6_distinct_digits
      CHECK (cardinality(uniq(sort(string_to_array(mycode, NULL)::int[]))) = 6)
);