SQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
A check constraint can NOT be defined on a SQL View.

The CHECK constraint ensures that you can not have any Student below 20 years:

Example:
CREATE TABLE Student(
    ID int NOT NULL,
    Name varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int CHECK (Age>=20)
);

Check Constraint on Alter Table
ALTER TABLE Student
ADD CONSTRAINT CHK_StudentAge CHECK (Age>=20 AND Name='Subha');
DROP a CHECK Constraint
ALTER TABLE Student
DROP CONSTRAINT CHK_StudentAge;
Check Constraint Using for Trigger

Example:


Create TRIGGER TransBalanceDet ON [dbo].[Sudent] 
FOR UPDATE
AS
 declare @Age int;
 declare @Name int;
 
 select @Age=i.Age  from inserted i; 
 select @Name=i.Name  from inserted i; 
 
 
 if (@Age<20 and Name='Subha')
 BEGIN
       RAISERROR('Record(s) are not allowed!',16,1);
       ROLLBACK;
 END 
END

Post a Comment

0 Comments