不刪除Oracle中資料的情況下,改欄位類型

來源:互聯網
上載者:User

--修改INFO_CUS_COMPLEX_TAX序號類型
alter table INFO_CUS_COMPLEX_TAX  add AA number;
-- Add/modify columns
alter table  INFO_CUS_COMPLEX_TAX  modify NO null;
--禁用約束
alter table INFO_CUS_COMPLEX_TAX disable constraint PK_INFO_COMPLEX_TAX1;
update  INFO_CUS_COMPLEX_TAX  set AA=NO,NO=null;
commit;
alter table  INFO_CUS_COMPLEX_TAX  modify NO number(4);
update  INFO_CUS_COMPLEX_TAX  set NO=AA,AA=null;
commit;
alter table  INFO_CUS_COMPLEX_TAX  drop column AA;
alter table  INFO_CUS_COMPLEX_TAX  modify NO not null;
--啟用約束

alter table INFO_CUS_COMPLEX_TAX enable constraint PK_INFO_COMPLEX_TAX1;

問題:探索資料庫出現當約束禁用/刪除後,與它對應的索引並沒有被刪除,導致在將NO列的值賦給AA列時依然報違反唯一約束

正常情況:當約束被禁用/刪除後,與它對應的索引應該會被刪掉,當約束被啟用/建立時,再重新建立

可能的原因:

在建立約束的時候,Oracle會自動建立對應的索引,這兩者是關聯的,當約束被禁用/刪除時,對應的索引會被刪掉,當啟用/建立時,對應的索引會被建立,但是如果先建索引後建約束,即使兩者的名字,關聯欄位一致他們也是沒有關係的,看上去和上面一樣,這時就會出現上面的問題。

解決辦法1:判斷那個索引是否存在

指令碼:

declare
V_Count varchar2(2);
begin
--修改INFO_CUS_COMPLEX_TAX序號類型
execute immediate 'alter table INFO_CUS_COMPLEX_TAX  add AA number';
-- Add/modify columns
execute immediate 'alter table  INFO_CUS_COMPLEX_TAX  modify NO null';
--禁用約束
execute immediate 'alter table INFO_CUS_COMPLEX_TAX disable constraint PK_INFO_COMPLEX_TAX1';

select count(t.status) into V_Count from user_indexes t where t.index_name='PK_INFO_COMPLEX_TAX1';
if (V_Count>0) then
   execute immediate 'drop index PK_INFO_COMPLEX_TAX1';
end if;

execute immediate 'update  INFO_CUS_COMPLEX_TAX  set AA=NO,NO=null';
execute immediate 'alter table  INFO_CUS_COMPLEX_TAX  modify NO number(4)';

execute immediate 'update  INFO_CUS_COMPLEX_TAX  set NO=AA,AA=null';
commit;
execute immediate 'alter table  INFO_CUS_COMPLEX_TAX  drop column AA';
execute immediate 'alter table  INFO_CUS_COMPLEX_TAX  modify NO not null';
--啟用約束
execute immediate 'alter table INFO_CUS_COMPLEX_TAX enable constraint PK_INFO_COMPLEX_TAX1';

end;

解決方案2:採用串聯刪除
alter table tvehicle drop constraint CHECK_ONLY cascade drop index;
再重新建立索引

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.