Elad Benda Elad Benda - 2 days ago 5
SQL Question

How to add multiple columns to a table and add default constraint on one of them?

I want to add 2 new columns to existing table.

One of them should be

NOT NULL
with default value 0
(filled in the existing rows as well).

I have tried the following syntax:

Alter TABLE dbo.MamConfiguration
add [IsLimitedByNumOfUsers] [bit] NOT NULL,
CONSTRAINT IsLimitedByNumOfUsers_Defualt [IsLimitedByNumOfUsers] DEFAULT 0
[NumOfUsersLimit] [int] NULL
go


But it throws exception. How should I write it?

Answer

You can use this :

ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL DEFAULT 0,   
    [NumOfUsersLimit] [INT] NULL
GO

Or

ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL 
        CONSTRAINT IsLimitedByNumOfUsers_Defualt DEFAULT 0,
    [NumOfUsersLimit] [INT] NULL
go

More : ALTER TABLE

Comments