SQL Server 2008检查约束不起作用

时间:2018-03-06 07:54:43

标签: sql-server sql-server-2008 tsql

CREATE TABLE [dbo].[StateMaster]([StateId] [int] IDENTITY(1,1) NOT NULL,[StateName] [varchar](30) NOT NULL,[IsDisable] [bit] NOT NULL,CONSTRAINT CHK_StateDisable CHECK *(**IsDisable>=0 and IsDisable<=1**)*,
CONSTRAINT [PK_StateMaster] PRIMARY KEY CLUSTERED 
(
    [StateId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[StateMaster] ADD  CONSTRAINT [DF_StateMaster_IsDisable]  DEFAULT ((0)) FOR [IsDisable]
GO

执行此插入后:

insert into StateMaster values ('ABC',***2***)`

我得到了这个输出:

select * from StateMaster


StateId StateName   IsDisable
1       ABC         **1**

1 个答案:

答案 0 :(得分:3)

您没有获得预期的输出,因为您将列IsDisable定义为BIT,只能接受True / False或1/0。因此,对于BIT数据类型,除0NULL之外的所有值均为1。

SELECT CAST(NULL AS BIT),
       CAST(0 AS BIT),
       CAST(1 AS BIT),
       CAST(4 AS BIT);

为您提供以下结果

enter image description here

因此,您可以尝试将IsDisable的数据类型更改为INT,然后尝试使用相同的插入内容。 Iwillll会抛出以下错误

  

消息547,级别16,状态0,行17 INSERT语句冲突   使用CHECK约束“CHK_StateDisable”。冲突发生在   数据库“MyDb”,表“dbo.StateMaster”,列“IsDisable”。该   声明已被终止。