Am creating a table name Table1,
CREATE TABLE Table1(id int primary key,nam varchar(10))
I am creating the second table Table2.
CREATE TABLE Table2(id1 int primary key, nam varchar(10))
Now, am trying to link these two tables using a column named id in first table with id in the second table.
ALTER TABLE Table2
ADD FOREIGN KEY (ID1) REFERENCES
Table1(ID)
Foreign key: It forms a relation ship between the Master table and Child table.
Here Table1 is the master table where as, Table2 is the child table.
It inturns define a basic rule, "Master table should have a record before inserting into child table".
Let's try to insert some data in the child table without inserting appropriate records in the master table.
INSERT INTO Table2 VALUES(2,'VP')
We will get an error indicating, foreign key constraint wont allow for this.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Table2__id1__2898D86D".
The conflict occurred in database "master", table "dbo.Table1", column 'id'.
Let me try to insert some value in master table.
INSERT INTO Table1 VALUES(2,'VP')
Output is,
(1 row(s) affected)
Let's make a try with Table2.
INSERT INTO Table2 VALUES(2,'VP')
Output is,
(1 row(s) affected)
Hope its clear!!!
Happy Learning!!!
Regards,
Venkatesan Prabu .J
No comments:
Post a Comment