Tuesday, June 26, 2012

How to Add Constarint in Table Create Command

CREATE TABLE ProductSales(SalesID INT,ProductID INT,SalesPerson VARCHAR(25)CONSTRAINT pk_productSales_sid PRIMARY KEY(SalesID),CONSTRAINT fk_productSales_pidFOREIGN KEY(ProductID)REFERENCES Products(ProductID) ON DELETE CASCADE
);



You can specify ON DELETE CASCADE also in Foreign Key Constraint
You Can also Create Foreign Key constraint Like this......


CREATE TABLE Orders
(
O_Id INT NOT NULL,
OrderNo INT NOT NULL,
P_Id INT,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)



You Can Also Add Constraint by Using Alter Command also 


ALTER TABLE ProductSalesADD CONSTRAINT fk_productSales_pid FOREIGN KEY(ProductID)REFERENCES Products(ProductID)

No comments:

Post a Comment