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

早过忘川 提交于 2019-12-01 15:03:34

问题


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 pks


回答1:


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)



回答2:


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)
)



回答3:


you cant have 2 primary keys but you can have a composite primary key, which is a key made of two columns, which is exactly what you got on the [SalesOrderDetail] table with [SalesOrderID] and [SalesOrderDetailID]




回答4:


CREATE TABLE [dbo].[tab2](  
    [col1] [int] NOT NULL, 
    [col2] [int] NOT NULL, 
    [col3] [nchar](10) NOT NULL,  
    [col4] [nchar](10) NOT NULL,   
 CONSTRAINT [PK_tab2] PRIMARY KEY CLUSTERED    
(  
    [col1] ASC, 
    [col2] ASC 
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]  
) ON [PRIMARY] 


来源:https://stackoverflow.com/questions/11578703/how-to-set-combine-two-primary-keys-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!