位类型:默认为“0”而不是NULL

时间:2017-05-16 08:42:48

标签: sql-server

默认情况下,sql server为boolean字段分配NULL值。 如何告诉它使用'0'作为默认值? 我尝试将默认值设置为((0))但它仍然存在于NULL。

5 个答案:

答案 0 :(得分:7)

Here's a sample with a non nullable bit column with the default specified, just run the below in Management Studio:

CREATE TABLE #temp
    (
      id INT ,
      myBit BIT NOT NULL DEFAULT 0  -- not null with default of false
    );

INSERT  INTO #temp
        ( id )  -- only insert to id col, the default will set itself
VALUES  ( 123 );

INSERT INTO #temp
        ( id, myBit )
VALUES  ( 456, 1 )  -- this insert adds a true value to override the default

SELECT  *
FROM    #temp;

DROP TABLE #temp;

Produces:

id  myBit
123 0
456 1

答案 1 :(得分:1)

ALTER TABLE 表名 ADD 列名 BIT NOT NULL DEFAULT 0;

答案 2 :(得分:1)

I would recommend to specify default name, otherwise generated name is not telling you anything about created constraint, see sample below:

CREATE TABLE TBL_SAMPLE
(
    ID INT NOT NULL CONSTRAINT [PK_ID] PRIMARY KEY,
    BIT_COLUMN BIT NOT NULL CONSTRAINT [DF_BIT_COLUMN] DEFAULT (0)
)
GO


INSERT INTO TBL_SAMPLE (ID)
VALUES (1)
GO

SELECT * FROM TBL_SAMPLE
GO

DROP TABLE TBL_SAMPLE
GO

EDIT:

CREATE TABLE #TBL_SAMPLE 
(
    ID INT NOT NULL CONSTRAINT [PK_ID] PRIMARY KEY,
    BIT_COLUMN BIT NULL --CONSTRAINT [DF_BIT_COLUMN] DEFAULT (0) 
) 
GO


INSERT INTO #TBL_SAMPLE (ID) VALUES (1) 
GO

SELECT * FROM #TBL_SAMPLE 
GO

ALTER TABLE #TBL_SAMPLE ADD CONSTRAINT [DF_BIT_COLUMN] DEFAULT (0) FOR BIT_COLUMN 
GO


INSERT INTO #TBL_SAMPLE (ID) VALUES (2) 
INSERT INTO #TBL_SAMPLE (ID) VALUES (3) 
GO

SELECT * FROM #TBL_SAMPLE 
GO

UPDATE #TBL_SAMPLE 
SET BIT_COLUMN = 0 
WHERE BIT_COLUMN IS NULL

SELECT * FROM #TBL_SAMPLE 
GO

DROP TABLE #TBL_SAMPLE 
GO

答案 3 :(得分:0)

ALTER TABLE(表名)ADD(列名)BIT NOT NULL默认值0;

答案 4 :(得分:-1)

请添加后缀WITH VALUES,如下所示。效果很好:

ALTER TABLE (your table) 
ADD (your column) [bit] NULL DEFAULT 1 WITH VALUES;