Search

Thursday, March 13, 2014
0 comments

How to apply Check on Constraint on Column in SQL

6:38 PMThursday, March 13, 2014
A check constraint enforces domain integrity by restricting the values to be inserted in a column. It is possible to define multiple check constraints on a single column. These are evaluated in the order in which they are defined. The syntax of applying the check constraint is:

CREATE TABLE table_name
(
Col_name [CONSTRAINT onstraint_name] CHECK (expression)
(col_name [, col_name [, …]])
.
)
A single check constraint can be applied to multiple columns when it is defined at the table level
Where,

  • Constraint_name specifies the name of the constraint to be created.
  • Expression specifies the conditions that define the check to be made on the column. Expression can include elements, such as arithmetic operators, relational operators, o keywords, such as IN, LIKE, and BETWEEN.

A check constraint can be specified by using the following keywords:

  • IN: To ensure that the values entered are from a list of constant expressions.
  • LIKE: To ensure that the value entered in specific column are of a certain pattern. This can be achieved by using wildcards.
  • BETWEEN: To specify a range of constant expressions by using the BETWEEN keyword. The upper and lower boundary values are included in the range.

The rules regarding the creation of the CHECK constraint are as follows:

  • It can be created at the column level.
  • It can contain user-specified search conditions.
  • It cannot contain subqueries.
  • It does not check the existing data in the table if created with the WITH NOCHECK option.
  • It can reference other columns of the same table.

In the example of the EmployeeLeave table, you need to ensure that the leave type can take any one of the three values: CL, PL, or SL. For this, while creating the table, you can add the check constraint using the IN keyword for the LeaveType column

You can use the following statement to apply the check constraint:

CREATE TABLE HumanResources.EmployeeLeave
(
EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee (EmployeeID),
LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY (EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL,
LeaveReson varchar(100),
LeaveType char (2) CONSTRAINT chkLeave CHECK (LeaveType IN (‘CL’, ‘SL’, ‘PL’))
)

The preceding command creates the EmployeeLeave table with a check constraint on the LeaveType column. The name of the constraint is chkLeave.
Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top