SQL 如何将复合主键添加到表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1350990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:23:27  来源:igfitidea点击:

How to add composite primary key to table

sqlsql-server-2005foreign-keysprimary-key

提问by Domnic

create table d(id numeric(1), code varchar(2))

After I create the above table how can I add a composite primary key on both fields and also a foreign key?

创建上表后,如何在两个字段和外键上添加复合主键?

回答by Chris W

alter table d add constraint pkc_Name primary key (id, code)

alter table d add constraint pkc_Name primary key (id, code)

should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

应该这样做。根据您使用的数据库,基本主键/索引有很多选项。

回答by Simon Nickerson

In Oracle, you could do this:

在 Oracle 中,您可以这样做:

create table D (
  ID numeric(1),
  CODE varchar(2),
  constraint PK_D primary key (ID, CODE)
);

回答by Thilo

The ALTER TABLEstatement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

ALTER TABLEChris 提出的语句应该有效,但首先您需要声明 columns NOT NULL。主键的所有部分都必须是NOT NULL.

回答by Jon Crowell

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

您无需先创建表,然后在后续步骤中添加键。您可以在创建表时添加主键和外键:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

此示例假设存在Codes我们希望使用外键引用的表 ( )。

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

如果您没有可供我们参考的表格,请添加这样的表格,以便示例能够正常工作:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE:you must have a table to reference before creating the foreign key.

注意:在创建外键之前,您必须有一个要引用的表。

回答by Brent

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

如果使用 Sql Server Management Studio Designer,只需选择两行(Shift+单击)并设置主键。

enter image description here

在此处输入图片说明