如何使用多个 LIKE 语句正确设置 CHECK 约束?

How to correctly setup CHECK constraint with multiple LIKE statements?

我正在尝试执行一个简单的规则来插入 bank_account 列的值:

 - bank account can consist of only digits
 - bank account can have one hyphen '-' or zero hyphens
 - bank account can have one slash '/' or zero slashes

我有这个检查约束:

alter table someTable
add constraint chk_bank check
(
    (bank_account not like '%-%-%')
    and
    (bank_account not like '%/%/%')
    and
    (bank_account not like '%[^0123456789\-/]%')
)

我有这些 bank_account 个数字(它们是虚构的):

12-4414424434/0987
987654321/9999
NULL
41-101010101010/0011
500501502503/7410
NULL
60-6000070000/1234
7987-42516/7845
NULL
12-12121212/2121

启用约束时出现此错误:

The ALTER TABLE statement conflicted with the CHECK constraint "chk_bank".
The conflict occurred in database "x", table "someTable", column 'bank_account'.

我尝试了一些 select 查询,但找不到错误的号码。

我的检查约束写错了吗?如果是这样,我应该如何更改它以满足我的要求? 检查约束是否忽略 NULL 值或这些是否有问题?

检查逻辑的简单方法是单独 select 条件,例如:

select bank_account,
  case when bank_account not like '%-%-%' then 1 else 0 end as CheckHyphens,
  case when bank_account not like '%/%/%' then 1 else 0 end as CheckSlashes,
  case when bank_account not like '%[^0123456789\-/]%' then 1 else 0 end as CheckIllegalCharacters,
  case when bank_account not like '%[^0123456789\-/]%' escape '\' then 1 else 0 end as CheckIllegalCharactersWithEscape
  from YourTable;

很明显你的最后一个条件不成立。添加 escape 子句可更正模式。

According to the documentation,默认没有转义符。您必须使用 escape 子句来表示反斜杠是转义字符:

...and bank_account not like %[^0123456789\-/]%' escape '\'...