User Id :    Password :      New Member   Forgot Password  
 
How to set default value in a column in Database table
Description Sometimes we need to set some default value in the table column when a row is created. Here I will show how to we can achieve it.   No. of Views     1295
  Rating     0
Author Anshu Rastogi   Posted On     11 Oct 2010
Tags SQL SERVER,SQL SERVER : How To    

Sample Code   Download Code

Introduction

Sometimes we need to set some default value in a column in a table when a row is created and we don't actually want to pass value to this column.

Here is code to set default value.

To set default value while creating new table

CREATE TABLE myTable
(
EmpId int NOT NULL PRIMARY KEY,
FirstName varchar(50) NOT NULL,
EmpLastName varchar(50),
ProjectId INT,
IsActive INT DEFAULT 1 
)

In the code above I have set default value for IsActive column. So when ever a row is created and user dont pass any data to this column value 1 will be automatically assigned to it.

To set default value on an existing column, do the following

ALTER TABLE myTable ADD CONSTRAINT IsActive_def DEFAULT 1 FOR IsActive

Here in the code above I have created a constraint IsActive_def on IsActive column and set default value 1. 

About Author

About Author N/A Anshu
No Photo
 
Country N/A
Company NetEdge Computing Solutions
Home Page N/A

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code