設置db2主鍵問題出錯的話,應該如何處理呢?下面就教您一個不允許設置db2主鍵問題的解決方法,希望對您學習設置db2主鍵方面有所幫助。
將empno設置為主鍵
db2 => alter table emp add primary key (empno)
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0542N "EMPNO" cannot be a column of a primary key or unique key because it
can contain null values. SQLSTATE=42831
fenced 出現問題的原因是,因為empno列在創建的時候,默認支持值為空。而在DB2中,針對這種情況,是不允許創建主鍵的。這點也與Oracle和MySQL不同。
fenced 因此,我們要添加主鍵,需要先修改empno,添加上約束,讓此列為非空:
db2 => alter table emp alter column empno set not null
將列修改了之後,嘗試添加主鍵,再次出錯:
db2 => alter table emp add primary key (empno)
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0668N Operation not allowed for reason code "7" on table "DB2INST1.EMP".
SQLSTATE=57016
解決辦法:
查看錯誤信息代碼SQL0668N,去查看具體的code“7”的含義。
db2 => ? SQL0668N
SQL0668N Operation not allowed for reason code "<reason-code>" on table
"<table-name>".
Explanation:
Access to table "<table-name>" is restricted. The cause is based on the
following reason codes "<reason-code>":
1fenced
fenced The table is in the Set Integrity Pending No Access state.
。。。。。內容省略。。。。。。。。
7fencedThe table is in the reorg pending state. This can occur after
fenced an ALTER TABLE statement containing a REORG-recommended
fenced Operation.
User response:
1fencedExecute the SET INTEGRITY statement with the IMMEDIATE CHECKED
fenced option on table "<table-name>" to bring the table out of the
。。。。。內容省略。。。。。。。。
7fencedReorganize the table using the REORG TABLE command.
fenced For a table in the reorg pending state, note that the following
fenced clauses are not allowed when reorganizing the table:
fenced
fenced * The INPLACE REORG TABLE clause
fenced * The ON DATA PARTITION clause for a partitioned table when
fenced table has nonpartitioned indexes defined on the table
通過查看上述描述中的紅色部分的文字,emp表的empno列是添加了not null約束而導致表出於了“reorg pending state”這種狀態。我們可以通過以下的方法來驗證:
db2 => load query table emp
Tablestate:
Reorg Pending
解決辦法,參照6.1中的“User response”描述,使用REORG TABLE命令:
db2 => reorg table emp
DB20000I The REORG command completed successfully.
修改完成後,再次添加主鍵:
db2 => alter table emp add primary key(empno)
DB20000I The SQL command completed successfully.
查看下表的狀態,若為normal則能夠正常得進行操作:
db2 => load query table emp
Tablestate:
Normal
總結:對表添加主鍵時出現的錯誤,是由於之前對表的列進行了修改,添加了非空約束,導致整個表出於“Reorg Pending”狀態。
針對表出現這種狀況時,使用reorg table命令,將表進行reorganize即可。