UPDATE 陷阱

update 用其他数据表的数据更新时,如果不加条件限制,则会更新全部数据,产生意想不到的结果

1.创建数据表

CREATE TABLE TEMP_TEST(
  IDN NUMBER,
  NM  VARCHAR2(10)
);

2.插入数据

INSERT INTO TEMP_TEST VALUES(1, 'A');
INSERT INTO TEMP_TEST VALUES(2, 'D');
INSERT INTO TEMP_TEST VALUES(3, 'C');
INSERT INTO TEMP_TEST VALUES(4, 'D');
COMMIT;

UPDATE 陷阱_第1张图片

3.错误的更新

打算更新表中IDN为2的数据NM为HELLO, 更新后其他数据匹配到的数据更新,未匹配到的被置为NULL

UPDATE TEMP_TEST T
SET T.NM =
(   WITH WA AS (SELECT 2 IDN, 'HELLO' AS NM FROM DUAL)
     SELECT NM
       FROM WA A
      WHERE A.IDN = T.IDN
);

UPDATE 陷阱_第2张图片

4.正确的更新

!更新是要加上更新的范围

UPDATE TEMP_TEST T
SET T.NM =
(   WITH WA AS (SELECT 2 IDN, 'HELLO' AS NM FROM DUAL)
     SELECT NM
       FROM WA A
      WHERE A.IDN = T.IDN
)
WHERE  EXISTS(
  WITH WA AS (SELECT 2 IDN, 'HELLO' AS NM FROM DUAL)
  SELECT 1 FROM WA B WHERE B.IDN = T.IDN   
);

UPDATE 陷阱_第3张图片

5.建议数据更新的时候使用 MERGE INTO 语句

你可能感兴趣的:(Oracle,Sql)