SQL 使用现有主键在 DB2 中添加现有列作为主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15152159/
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 13:58:37  来源:igfitidea点击:

Adding existing column as primary key in DB2 with existing primary keys

sqldb2

提问by Vicky

I have a table MY_TABLE in DB2 containing several columns:

我在 DB2 中有一个表 MY_TABLE 包含几列:

PRODUCT_ID
ADDED_DT
PRODUCT_NAME
PRODUCT_COLOR
PRODUCT_PRICE
EXPIRY_DT

Out of these columns, below columns form the primary key:

在这些列中,下面的列构成主键:

PRODUCT_ID
ADDED_DT

I want to add EXPIRY_DT as primary key such that the table will now have three primary keys viz. PRODUCT_ID, ADDED_DT and EXPIRY_DT

我想添加 EXPIRY_DT 作为主键,这样表现在将有三个主键,即。PRODUCT_ID、ADDED_DT 和 EXPIRY_DT

I tried below set of commands:

我尝试了以下命令集:

ALTER TABLE MY_TABLE ADD PRIMARY KEY (EXPIRY_DT);
REORG TABLE MY_TABLE;

However, the query failed with error:

但是,查询失败并出现错误:

Table "MY_TABLE" already has a "PRIMARY" key.

How to acheive this ?

如何实现这一目标?

回答by andy

First you need to drop the existing primary key and then add new primary key

首先你需要删除现有的主键,然后添加新的主键

ALTER TABLE Table_Name DROP PRIMARY KEY;

ALTER TABLE Table_Name ADD PRIMARY KEY (Column_One, Column_Two);