Thursday, September 13, 2012

Check Constraint in SQL-Server

Posted by Rahul Kharde at 11:45 PM

A check constraint is a rule that identifies acceptable column values for data in a row within a SQL Server table. The CHECK constraint ensures that all values in a column satisfy certain conditions.

Example

We will create an Employee table with Check constraint,

Employee Table contain Employee ID, Name and Age.

We set Check constraint property on Age column. Age should not be less than 18

Create table of Employee as follows.

CREATE TABLE Employee

(

EID INT PRIMARY KEY IDENTITY,

ENAME VARCHAR(100),

EAGE INT

CHECK (EAGE>18)

)

Try to insert the below records


INSERT INTO Employee(ENAME,EAGE)VALUES('ABC',20)


Check Constraint allowed to insert record in to the Employee table.but when we try to insert below record, it will shows an error Message


INSERT INTO Employee(ENAME,EAGE)VALUES('PQR',15)


Msg 547, Level 16, State 0, Line 1

The INSERT statement conflicted with the CHECK constraint "CK__Employee__EAGE__5AEE82B9". The conflict occurred in database "XXXX", table "dbo.Employee", column 'EAGE'.

The statement has been terminated.

Employee Contain only first record

SELECT * FROM Employee



If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top