tsql - 如何使用多个 LIKE 语句正确设置 CHECK 约束?
问题描述
我正在尝试执行一个简单的规则来插入 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\-/]%')
)
我有这些银行帐号(它们是虚构的):
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'.
我尝试了一些选择查询,但找不到错误的数字。
我的检查约束写错了吗?如果是这样,我应该如何更改它以符合我的要求?检查约束是否忽略 NULL 值或者这些是一个问题?
解决方案
检查逻辑的简单方法是单独选择条件,例如:
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
子句可以纠正这种模式。
推荐阅读
- reactjs - 图标字体并不总是在反应应用程序中正确加载
- java - 如何在招摇中隐藏空组?
- mysql - 仅当他们有关于 1 个表的信息时才加入 3 个表
- flutter - 如何使用列制作这种类型的 TextButton?在颤振中
- r - 是否可以在 R 中使用带有 cv.glmnet 的滚动交叉验证?
- javascript - 如何在运行时检查文字对象是否与类型或接口一致?
- html - 对齐 div 以从具有不同宽度的同一垂直线开始
- flutter - Flutter:如何让卡片扩展到整个屏幕?
- mysql - mysqldump 在尝试导出到 csv 时给出 You must use option --tab with --fields-... 错误
- python - 使用python进行文本数据聚类