28

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

51

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

3
  • 5
    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
    Mar 3, 2013 at 11:57
  • 1
    @marc_s: yeah, I strongly agree with you! Mar 3, 2013 at 11:58
  • 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!
    – Mike
    Oct 12, 2018 at 19:34
6

Try this.

ALTER TABLE dbo.MamConfiguration  
ADD [IsLimitedByNumOfUsers] [bit]  NOT NULL DEFAULT 0,     
[NumOfUsersLimit] [int] NULL  
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
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.