DB2 新增主鍵 -542, SQLSTATE=42831
阿新 • • 發佈:2021-01-28
1.問題
需要對錶進行增加主鍵時,使用如下語句:
alter table TABLENAME add primary key (PK_FIELD);
發生錯誤:
-542, SQLSTATE=42831
解釋:
-542 42831 :可以為空的列不允許作為主鍵的一部分包含在內
檢查表結構 發現 PK_FIELD 確實是允許為空
SELECT * from SYSIBM.SYSCOLUMNS where TBNAME='TABLENAME';
2.解決方案
1. 將Allow null 改為 not null
執行
alter table TABLENAME ALTER PK_FIELD set not null;
網上也有如下語句,但發現在有資料的情況下無法更正 allow null為not null
alter table TABLENAME add unique(PK_FIELD);
2. 設定主鍵
alter table TABLENAME add primary key (PK_FIELD);
*如果在執行alert後發現出現錯誤
SQL0668N Operation not allowed for reason code “7” on table XXX
請重新整理下表
call sysproc.admin_cmd ('reorg table TABLENAME' );
綜上所述
大致過程如下:
alter table TABLENAME ALTER PK_FIELD set not null;
alter table TABLENAME add primary key (PK_FIELD);
call sysproc.admin_cmd ('reorg table TABLENAME');