29

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?

4 Answers 4

56

You can use this:

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

or this:

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

More: ALTER TABLE

Sign up to request clarification or add additional context in comments.

3 Comments

I would always recommend option #2 - give your constraints explicit names - makes it a lot easier if you need to drop them later on!
@marc_s: yeah, I strongly agree with you!
I never noticed that you could use a , between columns to be added. What a time saver if you are adding a lot of new columns to an existing table!
6

Try this.

ALTER TABLE dbo.MamConfiguration  
ADD [IsLimitedByNumOfUsers] [bit]  NOT NULL DEFAULT 0,     
[NumOfUsersLimit] [int] NULL  

Comments

0

To add multiple columns to a table and add default constraint on one of them-

ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] CONSTRAINT Def_IsLimitedByNumOfUsers DEFAULT(0) NOT NULL,   
    [NumOfUsersLimit] [INT] NULL;
GO

Comments

0

Each column is different;

ALTER TABLE
    MamConfiguration
ADD
    Configuration1 BIT NULL, --this column is nullable
    Configuration2 BIT NOT NULL, --this column is not nullable
    Configuration3 BIT NOT NULL DEFAULT(0), --this column is not nullable and set default value is 0(zero)
    Configuration4 BIT NOT NULL CONSTRAINT DF_Configuration4 DEFAULT(0) --this column is not nullable and set default value is 0(zero) with spesific constraint name
GO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.