September 12, 2013 at 6:38 am
i want to create Primary key for 3 columns in parent table
and foreign key in for 2 coloumns in child table.
can i refer these 2 foreign key columns to those 3 primary key columns ?
September 12, 2013 at 7:47 am
Can you post your DDL?
If I understand what you are asking, it isn't possible. A foreign key must reference a primary key or unique constraint on the referenced table it can't reference a partial PK or unique constraint. Easy enough to test with this code:
CREATE TABLE dbo.parent
(
col1 INT,
col2 INT,
col3 INT,
CONSTRAINT PK_Parent PRIMARY KEY CLUSTERED (col1, col2, col3)
);
CREATE TABLE dbo.child
(
Col1 INT,
col2 INT,
CONSTRAINT FK_child_parent FOREIGN KEY (col1, col2) REFERENCES dbo.parent (col1, col2)
);
Jack Corbett
Consultant - Straight Path Solutions
Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
September 12, 2013 at 7:49 am
sreenubabu.s (9/12/2013)
i want to create Primary key for 3 columns in parent tableand foreign key in for 2 coloumns in child table.
can i refer these 2 foreign key columns to those 3 primary key columns ?
No. You can't do that. A foreign key is a column (or collection of columns for a composite key) used to identify the row in the parent. With only part of that information it is impossible to determine which row the child belongs to.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
September 12, 2013 at 8:12 am
The key, the whole key, and nothing but the key, so help me Codd.
When you define a key, that's what you have to use.
Now, if the two columns that you're interested in using as a foreign key in the child table are unique, you could create a unique constraint and then use that as a foreign key.
"The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
- Theodore Roosevelt
Author of:
SQL Server Execution Plans
SQL Server Query Performance Tuning
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply