如何在SQL Server 2008中设置默认值?

时间:2014-02-11 14:25:29

标签: sql-server sql-server-2008

我有大量数据存储在SQL Server 2008中。现在我想将[Book_ID]值{1}的新字段default添加到现有表中,但它不起作用。

code

CREATE TABLE [dbo].[Ayyat_Translation_Language_old_20131209] (
    [Ayat_Translation_Language_ID] INT            IDENTITY (1, 1) NOT NULL,
    [Translation_Laanguage_ID]     INT            NULL,
    [Juz_ID]                       INT            NULL,
    [Surah_ID]                     INT            NOT NULL,
    [Ayat_Description]             NVARCHAR (MAX) COLLATE Arabic_CI_AI_KS_WS NOT NULL,
    [Ayat_No]                      INT            NULL,
    [Book_ID]                      INT NULL DEFAULT 1, 
    PRIMARY KEY CLUSTERED ([Ayat_Translation_Language_ID] ASC),
    CONSTRAINT [fkey2] FOREIGN KEY ([Translation_Laanguage_ID]) REFERENCES [dbo].[Translation_Language] ([TransLation_Language_ID]) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT [fkey1] FOREIGN KEY ([Surah_ID]) REFERENCES [dbo].[Surah] ([Surah_ID]) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT [fkey0] FOREIGN KEY ([Juz_ID]) REFERENCES [dbo].[Juz] ([Juz_ID])
);

新字段已添加到表中,但它包含Null。任何帮助!

2 个答案:

答案 0 :(得分:1)

此行为取决于您插入数据的方式。如果在列中显式插入NULL,则它将采用NULL,而不是默认值。如果您希望它在默认情况下使用,请在插入期间完全省略Book_ID列(或者,您也可以使用关键字DEFAULT as a placeholder)。

e.g。这仍然会插入NULL:

INSERT INTO [dbo].[Ayyat_Translation_Language_old_20131209] 
(
    [Ayat_Translation_Language_ID], ,
    [Translation_Laanguage_ID]     ,
    [Juz_ID]                       ,
    [Surah_ID]                     ,
    [Ayat_Description]             ,
    [Ayat_No]                      ,
    [Book_ID]                      
)
VALUES (1, 2, 3, 4, 'Foo', 5, NULL); 

这将采用默认值:

INSERT INTO [dbo].[Ayyat_Translation_Language_old_20131209] 
(
    [Ayat_Translation_Language_ID], ,
    [Translation_Laanguage_ID]     ,
    [Juz_ID]                       ,
    [Surah_ID]                     ,
    [Ayat_Description]             ,
    [Ayat_No]
    -- BOOK_ID is omitted, or use DEFAULT
)
VALUES (1, 2, 3, 4, 'Foo', 5); 

答案 1 :(得分:0)

您现在需要将表更改为不接受Book_ID

的NULL
ALTER TABLE [dbo].[Ayyat_Translation_Language_old_20131209]
    ALTER COLUMN [Book_ID] INT NOT NULL DEFAULT 1

如果出现错误,您可能需要先更新现有记录:

UPDATE [dbo].[Ayyat_Translation_Language_old_20131209]
    SET [Book_ID] = 1