Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set (combine) two primary keys in a table

For a small sales related application, we designed database using logical data model. Come to the stage to convert in to physical model. While creating table in SQL Server Management Studio Express, according to our logical data model, we need to combine two attributes to form unique id. Is it possible to combine two primary keys and set it?

But while observing Northwind Sample, we found that in the ORDER DETAILS table, we can see two primary keys Order Id & Product Id. And according to rule table can't have two primary keys. So how it happened in Northwind?

In my case how should I set two columns in my table to make it as two primary keys?

Someone gave suggestion like

To make a two primary key, open the table in design view and click on the two of the required fields and holding CTL, apply primary key

Will this work ??

Edit ;

now my table have 2 PK's in the SSMS . is it valid or it is just a combinationof 2 pksenter image description here

like image 582
panindra Avatar asked Jul 20 '12 11:07

panindra


2 Answers

The easiest way would be to use a T-SQL command in SSMS Express rather than trying to use the visual designers.....

Once you've designed and created your table, try something like this:

ALTER TABLE dbo.YourTableNameHere
ADD CONSTRAINT PK_YourTableNameHere
PRIMARY KEY(Item_Id, Purchase_Id)
like image 161
marc_s Avatar answered Oct 07 '22 17:10

marc_s


you cannot create two primary keys in a table. You can combine two columns in a table and make as a single primary key

create table table1
(
col1 int,
col2 varchar(20),
....
Primary key (col1, col2)
)
like image 39
Joe G Joseph Avatar answered Oct 07 '22 18:10

Joe G Joseph