为什么zipcode没有检查约束?

时间:2017-11-12 23:35:33

标签: sql sql-server constraints

我觉得我可能遗漏了一些非常简单的东西,但我真的无法弄清楚我做错了什么。我试图使用检查约束来确保邮政编码是5位数字,但检查约束仍然失败。这是使用约束创建的表:

Create Table Students (
   StudentID Int Primary Key Identity(1,1)
   StudentNumber nVarchar(100) Unique Not Null,
   ...
   StudentZipCode nChar(10) Not Null
)
Go
Alter Table Students Add Constraint chZipCode
    CHECK (StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]' OR StudentZipCode 
    Like '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')
Go

代码如12345-6789有效,但当我尝试插入像' 12345'或者' 01234'它给了我这个错误:

INSERT语句与CHECK约束" chZipCode"冲突。冲突发生在数据库......,表" dbo.Students",column' StudentZipCode'。

1 个答案:

答案 0 :(得分:1)

它失败了,因为您将邮政编码定义为char()而不是varchar()。因此,它有一堆空格填充它。

因此,将其定义为:

Create Table Students (
   StudentID Int Primary Key Identity(1,1),
   StudentNumber nVarchar(100) Unique Not Null,
   StudentZipCode nVarChar(10) Not Null,
   CHECK (StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]' OR
          StudentZipCode LIKE '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')
);

然后'12345'有效,因为它与第一个LIKE模式匹配。

'012344'不起作用,因为没有模式连续六位数。

Here是一个SQL小提琴。

相关问题