Wednesday, March 21, 2012

SQL SERVER – Add Column With Default Column Constraint to Table


Setting a default value to a column in case a row in inserted with a no value provided for the column. Please find the below code to set a default value for a column. The example below adds a new column and applies the default constraint and default value of 'Hello' and the column doesn't allow null.


ALTER TABLE YourTable
ADD YourNewColumn VARCHAR(50)
CONSTRAINT DF_ YourTable_YourNewColumn DEFAULT 'Hello' NOT NULL
GO



Constraint name is not mandatory as SQL Server will take a default constraint name in case if you don't provide one.

2 comments:

  1. Great..
    Thanks a lot. Helped me a lot..

    ReplyDelete
  2. Thanks for sharing your knowledge. This really helped me.

    ReplyDelete