Oracle批量、大量Update方法總結
阿新 • • 發佈:2018-12-22
(1)主從兩個表,主表Student,有欄位id、name、sex,從表Boy,有欄位id、name,主從表同一物件id相同
(2)從表Boy的name屬性被業務修改,定時批量處理主表,以維持主表name屬性與從表一致
二、表結構:
1、主表 Student
2、從表 Boy
三、建表SQL:(庫名 "KU")
1、主表 Student
-- DDL CREATE TABLE "KU"."STUDENT" ( "ID" NUMBER NOT NULL , "NAME" VARCHAR2(255 BYTE) NULL , "SEX" VARCHAR2(255 BYTE) NULL ) ALTER TABLE "KU"."STUDENT" ADD CHECK ("ID" IS NOT NULL); -- DML INSERT INTO "KU"."STUDENT" VALUES ('1', 'zhangsan', 'boy'); INSERT INTO "KU"."STUDENT" VALUES ('2', 'lisi', 'girl'); INSERT INTO "KU"."STUDENT" VALUES ('3', 'wangwu', 'boy');
2、從表 Boy
-- DDL
CREATE TABLE "KU"."BOY" (
"ID" NUMBER NOT NULL ,
"NAME" VARCHAR2(255 BYTE) NULL
)
-- DML
INSERT INTO "KU"."BOY" VALUES ('1', '張三');
INSERT INTO "KU"."BOY" VALUES ('3', '王五');
四、DML
1、基本語法
-- DML
UPDATE student s SET s.name = '張三' WHERE id = 1;
2、變相
-- DML,0.015s UPDATE student s SET s.name = ( SELECT b.name FROM boy b WHERE s.id = b.id AND s.name != b.name ) WHERE EXISTS ( SELECT 1 FROM boy b WHERE s.id = b.id AND s.name != b.name );
3、快速遊標法
-- DML,0.014s
BEGIN
FOR cur IN (
SELECT s.id sid, b.name bname
FROM student s, boy b
WHERE s.id = b.id AND s.name != b.name AND s.sex = 'boy'
) loop
UPDATE student s SET s.name = cur.bname WHERE s.id = cur.sid;
END loop ;
END ;
4、內聯檢視法(inline View)
-- DML,0.019s UPDATE ( SELECT s.name sname, b.name bname FROM student s, boy b WHERE s.id = b.id AND s.name != b.name ) SET sname = bname;
報錯提示:ORA-01779: 無法修改與非鍵值儲存表對應的列
參考資料,從表id必須增加主鍵約束,且為檢視內的where條件:
-- DDL
ALTER TABLE boy ADD CONSTRAINT pk_id PRIMARY KEY (id);
5、合併法(Merge)
MERGE INTO student s USING boy b ON (
s.id = b.id AND s.sex = 'boy' AND s.name != b.name
)
WHEN MATCHED THEN
UPDATE SET s.name = b.name;
報錯提示:ORA-38104: 無法更新 ON 子句中引用的列
參考資料,條件重複:
-- DML,0.016s
MERGE INTO student s USING boy b ON (
s.id = b.id AND s.sex = 'boy'
-- AND s.name != b.name
)
WHEN MATCHED THEN
UPDATE SET s.name = b.name;
參考資料
【1】《Oracle in和exist的區別》
【2】《Merge無法更新ON子句》
【3】《無法修改與非鍵值儲存表對應的列》
【4】《Oracle的update語句優化》
---------------------
作者:maozexijr
來源:CSDN
原文:https://blog.csdn.net/MAOZEXIJR/article/details/81027059
版權宣告:本文為博主原創文章,轉載請附上博文連結!