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**
您没有得到预期的输出,因为您将列IsDisable
定义为BIT
,它只能接受True / False或1/0。所以对于BIT
数据类型,除0
和NULL
之外的所有值都是1。
SELECT CAST(NULL AS BIT),
CAST(0 AS BIT),
CAST(1 AS BIT),
CAST(4 AS BIT);
给你以下结果
因此,您可以尝试将IsDisable
的数据类型更改为INT
,然后尝试相同的插入。 Iwillll抛出以下错误
消息547,级别16,状态0,行17 INSERT语句与CHECK约束“CHK_StateDisable”冲突。冲突发生在数据库“MyDb”,表“dbo.StateMaster”,列“IsDisable”中。该语句已终止。