Oracle 常用操作【01】修改、更新數據


1. oracle 修改表名、列名、字段類型、添加表列、刪除表列 

alter table scott.test rename to test1--修改表名
alter table scott.test rename column name to name1 --修改表列名
alter table scott.test modify name1 number(20) --修改字段類型
alter table scott.test add address varchar2(40) --添加表列
alter table scott.test drop name cascadeconstraints --刪除表列

2. 將一個表B的(某幾個字段的數據)復制到新表A(某幾個不同的字段)中

insert into tableA (A, B) select C,D from tableB t;

3. 取出一個表集合,循環(更新,刪除,)另外一個表屬性(數據,注釋,結構),多用於數據表局部同步數據

begin
  for i in (select A.a, A.b from A) loop execute immediate 'update B set B.c =' || i.a || ' set B.d=' || i.b; end loop; end;

在字符串型的變量前面記得加 chr(39);

4. 更新字段數據為大寫(小寫)

  update A set A.a= upper(A.a); //大寫 update B set B.b = lower(B.b); //小寫

5. 更新數據表字段順序(有兩種方法)

方法一:

a.將原表的建表SQL,通過查看表結構,粘貼下來;

b.將准備更新表字段順序的數據表全表插入到臨時表中;

c.drop 掉你准備更新數據表;

d.修改你剛才粘貼出來的原表建表語句,修改其中的字段的順序為你想要的;

e.將臨時表中的數據插入到剛創建好的表,drop 掉臨時表;

 

方法二:

a.查看數據表物理ID;

select object_id from all_objects where owner='表的所有者' and object_name='具體的表';

b.通過上面的物理ID查看表的字段對應的物理順序;

select obj#,col#,name from sys.col$ where obj#=131347 order by col#;

c.更新對應的表字段的物理順序(這步更新需要數據庫超級管理員的權限,請慎用):

update sys.col$ set col#=5 where obj#=131347 and name='JKSE';

d.更新完畢之后,重啟數據庫;

   兩種方法對比,如果你們項目是協同開發,一個數據庫是多個人在使用,方法二並不適合你,因為你要重啟數據庫,會耽誤別人的開發時間。

   如果你SQL 語句寫的比較熟練,第一種方法,只會占用你大概5分鍾的時間,就能夠辦到你的想法;

6. 查詢和刪除重復記錄

1、查找表中多余的重復記錄,重復記錄是根據單個字段(Id)來判斷

select * fromwhere Id in (select Id fromgroup byId having count(Id) > 1)

2、刪除表中多余的重復記錄,重復記錄是根據單個字段(Id)來判斷,只留有rowid最小的記錄

DELETE fromWHERE (id) IN ( SELECT id FROMGROUP BY id HAVING COUNT(id) > 1) AND ROWID NOT IN (SELECT MIN(ROWID) FROMGROUP BY id HAVING COUNT(*) > 1);

3、查找表中多余的重復記錄(多個字段)

select * from 表 a where (a.Id,a.seq) in(select Id,seq fromgroup by Id,seq having count(*) > 1)

4、刪除表中多余的重復記錄(多個字段),只留有rowid最小的記錄

delete from 表 a where (a.Id,a.seq) in (select Id,seq fromgroup by Id,seq having count(*) > 1) and rowid not in (select min(rowid) fromgroup by Id,seq having count(*)>1)

5、查找表中多余的重復記錄(多個字段),不包含rowid最小的記錄

select * from 表 a where (a.Id,a.seq) in (select Id,seq fromgroup by Id,seq having count(*) > 1) and rowid not in (select min(rowid) fromgroup by Id,seq having count(*)>1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM