Click here to Skip to main content
15,913,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi friends, i m bishnu
i have a project and i want to make a foreign key which is primary key in another table

like.......... one table has table name tblEmployee where Employeeid is primary key and i have another table tblAttendance where Employeeid is wished to be made foreign key. i am using sqlserver express 2005. please help with query or code as soon as possible?
Posted
Comments
Sander Rossel 25-Oct-11 7:13am    
Are you asking about C# or SQL? C# does not have Primary Keys or Relations. Please be specific.

Hi,

The solution lies in SQL, not in c#.

You can add a foreign key to your field this way :

SQL
ALTER TABLE [tblAttendance]
ADD CONSTRAINT [FK_tblAttendance_tblEmployee]
FOREIGN KEY [Employeeid]
REFERENCES [tblEmplyee] ([Employeeid])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO


It is advised to also put an index on your foreign key :

SQL
CREATE INDEX [IX_FK_tblAttendance_tblEmployee]
ON [tblAttendance] ([Employeeid]);
GO
 
Share this answer
 
Comments
Mantu Singh 25-Oct-11 9:01am    
Nice details my 5!
phil.o 25-Oct-11 9:58am    
Thanks :)
If you are talking about DataRelation objects, then check this[^] out.

If you want to do this through code (for a table), then this forum discussion[^] should help you out.
 
Share this answer
 
Have you created the table already if no use this when you create it.........

Try this query

create table tblAttendance
(
Employeeid data_type foreign key refrences tblEmployee(Employeeid),
other_col data_type
)

In case table is already created use alter table as suggested by Mr philo
and try links provided by Mr Abhinav
Best of luck........
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900