CHECK() Constraint in SQL server is a data validation technique. Using CHECK() constraints, we can minimise data issues that could cause by bad application code or by incorrect queries by user at the database level.
Consider a table like below:
CREATE TABLE CourseSchedule (
courseId int NOT NULL,
course_year int NOT NULL,
course_start_date date,
course_end_date date,
PRIMARY KEY (courseId, course_year) )
Let's say we need users (or applications) to insert year as 4 digit year and year should be value between 2000 and 3000. Then we can define a check constraint like below.
CREATE TABLE CourseSchedule (
courseId int NOT NULL,
course_year int NOT NULL,
course_start_date date,
course_end_date date,
PRIMARY KEY (courseId, course_year),
CHECK(course_year >= 2000 and course_year <= 3000))
You can give a name to the constraint. This is really helpful when debugging issue. So you know which table and which column it happened.
E.g.
CREATE TABLE CourseSchedule (
courseId int NOT NULL,
course_year int NOT NULL,
course_start_date date,
course_end_date date,
PRIMARY KEY (courseId, course_year),
CONSTRAINT my_constraint1 CHECK(course_year >= 2000 and course_year <= 3000))
Check constraint can be declared in the line of the column, if it only applied to that column
E.g.
CREATE TABLE CourseSchedule (
courseId int NOT NULL,
course_year int NOT NULL CHECK(course_year >= 2000 AND course_year <= 3000),
course_start_date date,
course_end_date date,
PRIMARY KEY (courseId, course_year))
But if it reference multiple columns, it has to be on its own line.
E.g.
CREATE TABLE CourseSchedule (
courseId int NOT NULL,
course_year int NOT NULL,
course_start_date date,
course_end_date date,
PRIMARY KEY (courseId, course_year),
CONSTRAINT my_constraint2 CHECK(course_start_date <= course_end_date))
If you want to drop a check constraint:
ALTER TABLE CourseSchedule
DROP CONSTRAINT my_constraint2
No comments:
Post a Comment