You are on page 1of 3

Constraints

Not Null
USE SQLDemo
GO
CREATE TABLE ConstraintDemo1
(
       ID INT NOT NULL,
   Name VARCHAR(50) NULL
)

INSERT INTO ConstraintDemo1 ([ID],[NAME]) VALUES (1,'Ram')


GO
INSERT INTO ConstraintDemo1 ([ID]) VALUES (2)
GO
INSERT INTO ConstraintDemo1 ([NAME]) VALUES ('Ajay')
GO

ALTER TABLE ConstraintDemo1 ALTER COLUMN [Name] VARCHAR(50) NOT NULL

UPDATE ConstraintDemo1 SET [Name]='' WHERE [Name] IS NULL

Unique Constraint

CREATE TABLE ConstraintDemo2


(
     ID INT UNIQUE,
   Name VARCHAR(50) NULL
)

INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (1,'Ajay')


GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (2,'Ajay')
GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (NULL,'Vijay')
GO
INSERT INTO ConstraintDemo2 ([ID],[NAME]) VALUES (1,'vikas')
GO

SELECT CONSTRAINT_NAME,
     TABLE_SCHEMA ,
     TABLE_NAME,
     CONSTRAINT_TYPE
     FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
   WHERE TABLE_NAME='ConstraintDemo2'

ALTER TABLE ConstraintDemo2 DROP CONSTRAINT

ALTER TABLE ConstraintDemo2 ADD CONSTRAINT UQ__Constrai UNIQUE (ID)


GO

Primary Key

CREATE TABLE ConstraintDemo3


(
     ID INT PRIMARY KEY,
   Name VARCHAR(50) NULL
)

INSERT INTO ConstraintDemo3 ([ID],[NAME]) VALUES (1,'John')


GO
INSERT INTO ConstraintDemo3 ([NAME]) VALUES ('Rock')
GO
INSERT INTO ConstraintDemo3 ([ID],[NAME]) VALUES (1,'Lal')
GO

Check Constraint

CREATE TABLE cust_sample

cust_id int PRIMARY KEY,

cust_name char(50),

cust_address char(50),

cust_credit_limit money,

CONSTRAINT chk_id CHECK (cust_id BETWEEN 0 and 10000 )

Foreign Key

CREATE TABLE part_sample

(part_nmbr int PRIMARY KEY,

part_name char(30),

part_weight decimal(6,2),

part_color char(15) );

CREATE TABLE order_part

(order_nmbr int,

part_nmbr int

FOREIGN KEY REFERENCES part_sample(part_nmbr)

ON DELETE NO ACTION,

qty_ordered int);

GO

 NO ACTION specifies that the deletion fails with an error.

 CASCADE specifies that all the rows with foreign keys pointing to the
deleted row are also deleted.
 SET NULL specifies that all rows with foreign keys pointing to the deleted
row are set to NULL.

 SET DEFAULT specifies that all rows with foreign keys pointing to the
deleted row are set to their default value. For more information,
see Defaults.

Default Constraint
create table dbo.CustomerReport
(
customer_id int,
report_id int,
rundate datetime not null
constraint df_CustomerReport_rundate default getdate()
)
go

exec sp_helpconstraint [dbo.CustomerReport]


go

You might also like