Monday, June 15, 2009

Default constraint for Table column

Here it shows how to check a default constraint of column of a table and add a default constraint for that column


The syntax is given below.

Use
-----------
if exists(SELECT * FROM sysobjects WHERE xtype = 'D' AND name = '')
begin
alter table
drop constraint
end
alter table
add constraint default for


Example:

Here set the default value of JoinDate of employee table to current date as getdate(). So the defualt value joindate will be always the current date time.

/*
DB name:Department
Table Name:Employee
Column Name:JoinDate
constraint Name: DF_Employee_JoinDate
*/

Use Department
-----------
if exists(SELECT * FROM sysobjects WHERE xtype = 'D' AND name = 'DF_Employee_JoinDate')
begin
alter table dbo.Employee
drop constraint DF_Employee_JoinDate
end
alter table dbo.Employee
add constraint DF_Employee_JoinDate default getdate() for JoinDate

0 Comments: