Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I add foreign Key reference using Desgin or Query, it doesn't matter just i need to understand it very good . i will be so glad for an explanation about it .

I have Order table and has (CustomerFirstName, CustomerLastName,Id,RecivedAt) columns and i have also OrderItem table and has (Id,ItemNr, and OrderId which should be reference to Id in Order Table ) columns

I can't get that until now very well .

What I have tried:

here is the Query but please explain it clear .

Alter table .....
add constraint tbl..._...._FK FOREIGN KEY (...) references tbl(....)
Posted
Updated 29-Aug-19 7:13am

Please do your own research - this is a quick answers forum.

The following free resources will explain Foreign Keys fully:
Essential Guide to SQL Server FOREIGN KEY Constraint[^]
The Essential Guide To SQL Foreign Key Constraint[^]
 
Share this answer
 
Following is the explanation your query. Hopes this help you to get an idea.

According to your requirement OrderItem table is the parent table. Order table is the child table. So Order table is reference with the OrderItem table. Following is the querry for this purpose.

Alter table Order
add constraint tbl..._...._FK(constraint name) FOREIGN KEY (Id) references (OrderItem)
 
Share this answer
 
v2
Comments
CHill60 30-Aug-19 3:42am    
Completely the opposite of what is required. OrderItem is a child of Order so the FK should be in the OrderItem table - insisting that an Order must exist before an item can be added to it
[no name] 30-Aug-19 4:35am    
yes Chill60 you have right .
[no name] 30-Aug-19 4:37am    
Member 11511491, thanks for your answer but i meant the opposite (OrderItem) reference with Order
 
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