SQL Server 2008检查约束不起作用

问题描述 投票:1回答:1
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**
sql-server sql-server-2008 tsql
1个回答
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”中。该语句已终止。

© www.soinside.com 2019 - 2024. All rights reserved.