CREATE TABLE user1
(
id INT IDENTITY(1, 1),
name1 VARCHAR(20),
salary INT CONSTRAINT chk_sal CHECK (salary>2000)
--adding first check condition to filter database sal should be 2000
)
--entering data
INSERT INTO user1
VALUES ('Rambo',
23000)
INSERT INTO user1
VALUES ('John',
8000)
SELECT *
FROM user1
--Now what if we want to make changed into our check condition without effecting old data how it can be done
--1.Drop Existing Constraint
ALTER TABLE user1 DROP CONSTRAINT chk_sal
--2,Now add constraint again
ALTER TABLE user1 WITH NOCHECK ADD CONSTRAINT chk_sal CHECK(salary>9000)
SELECT *
FROM user1
INSERT INTO user1
VALUES ('Vertigo',
10000)
Listen to Your Daily Tune's
Sunday, September 19, 2010
Check Constraint Sql Server 2005 Part-2
Check Constraint Sql Server 2005
--check constraint it set's the particular condition until
--unless it is fulfill the record will not entered into the database
CREATE TABLE user2
(
id INT IDENTITY(1, 1),
name1 VARCHAR(20) CHECK (name1 LIKE '[%t%]'),
--checking name enter in database Should start from T
salary INT CHECK (salary>2000)
--Checking No Employee should get salary less than 2000
)
INSERT INTO user2
VALUES ('ramabo',
1000) -- will throw an execption as we made filter our database with check condition
INSERT INTO user2
VALUES ('t',
23000)
SELECT * FROM user2
Constraint's in Sql Server 2005-2008
--Constraint's in Sql Server 2005-2008
--Not Null and Default
CREATE TABLE user1
(
sno INT IDENTITY(1, 1),
id INT NOT NULL,-- means the value cannot be null/blank or we can say mandatory feild needs to be filled
name1 VARCHAR(20),
orderdate DATETIME DEFAULT Getdate(),--if entered as blank by default it will take current date
app_status VARCHAR(10) DEFAULT 'pending'--if status left blank by default for each id it will be pending
)
INSERT INTO user1
VALUES (101,
'john',
'2010-09-15',
'approved')
INSERT INTO user1
(id,
name1,
app_status)
VALUES (103,
'will',
'approved')
INSERT INTO user1
(id,
name1)
VALUES (104,
'sam')
SELECT * FROM user1