This constraint is used to map a particular column in the child table with a primary key column in the parent table. Consider my scenario, am having an employee table and it will be having empid as primary key (Unique reference to identify an employee) , am having empProjects which will hold project id as the primary key.
I need to check, In which project an employee is allocated? Or what are the projects assigned for this particular employee?
The relation ship between these two tables is One to Many relationship (An employee can work in more than one project).
To retrieve the result set we need to have a foreign key relation ship between the employee table and empProjects table, a column empid should be created in empProjects table and it should refer the primary table “Employee”.
Let’s see a small example; I am trying to create two tables VenkatA, VenkatB. Id in the second table is referencing the ‘id’ column in the primary table.
create table venkatA(id int,[name] varchar(100))
create table venkatB(id int references venkatA(id),designation varchar(100))
OOPS, On executing the query above, we will get an exception.
There are no primary or candidate keys in the referenced table 'venkatA' that match the referencing column list in the foreign key 'FK__venkatB__id__7BB05806'.
It’s because of the column ‘id’ in the primary table. It’s mandatory to declare that particular columns as primary or candidate key.
create table venkatA(id int primary key,[name] varchar(100))
create table venkatB(id int references venkatA(id),designation varchar(100))
On executing the query above, you will get the second table referencing the first one.
Thanks and Regards,
Venkatesan Prabu
No comments:
Post a Comment