如何停止更新oracle中的空值
How to stop updating null values in oracle
我有一个非常有效的 sql 程序。请在下面找到它。
declare
cid number;
cadd number;
ctras number;
pr varchar(2);
vad number;
cursor c1 IS
select ac_tras, cust_id, cust_addr from customer_master;
cursor c2 IS
select pr_adr from customer_address where cust_id = cid and cust_addr = cadd;
BEGIN
open c1;
LOOP
fetch c1 into ctras, cid, cadd;
EXIT WHEN C1%NOTFOUND;
OPEN c2;
LOOP
fetch c2 into pr;
if pr='Y'
THEN EXIT ;
ELSE
UPDATE customer_master
set cust_addr = (select cust_addr from customer_address where pr_adr = 'Y' and cust_id = cid) where ac_tras = ctras;
END IF;
EXIT WHEN C2%NOTFOUND;
END LOOP;
Close C2;
END LOOP;
CLOSE C1;
END;
一切正常。问题是,如果子查询 returns null,更新语句更新 null。如何避免这种情况。
如果子查询没有找到匹配的行,那么主查询 table 将更新为 null,因为没有过滤器可以阻止它。避免这种情况的常见方法是检查匹配行是否存在:
UPDATE customer_master
set cust_addr = (
select cust_addr from customer_address
where pr_adr = 'Y' and cust_id = cid)
where ac_tras = ctras
and exists (
select cust_addr from customer_address
where pr_adr = 'Y' and cust_id = cid)
;
在 exists
子句中使用哪个列名并不重要;有些人更喜欢使用 select *
或 select null
但这似乎真的是一个品味问题(除非你指定一个你以后不会使用的列并且不能从您正在使用的索引,这可能会强制执行不必要的 table 行查找)。
您也可以进行合并。 And has been pointed out several times now,您不需要光标或任何 PL/SQL 来执行此操作。
我有一个非常有效的 sql 程序。请在下面找到它。
declare
cid number;
cadd number;
ctras number;
pr varchar(2);
vad number;
cursor c1 IS
select ac_tras, cust_id, cust_addr from customer_master;
cursor c2 IS
select pr_adr from customer_address where cust_id = cid and cust_addr = cadd;
BEGIN
open c1;
LOOP
fetch c1 into ctras, cid, cadd;
EXIT WHEN C1%NOTFOUND;
OPEN c2;
LOOP
fetch c2 into pr;
if pr='Y'
THEN EXIT ;
ELSE
UPDATE customer_master
set cust_addr = (select cust_addr from customer_address where pr_adr = 'Y' and cust_id = cid) where ac_tras = ctras;
END IF;
EXIT WHEN C2%NOTFOUND;
END LOOP;
Close C2;
END LOOP;
CLOSE C1;
END;
一切正常。问题是,如果子查询 returns null,更新语句更新 null。如何避免这种情况。
如果子查询没有找到匹配的行,那么主查询 table 将更新为 null,因为没有过滤器可以阻止它。避免这种情况的常见方法是检查匹配行是否存在:
UPDATE customer_master
set cust_addr = (
select cust_addr from customer_address
where pr_adr = 'Y' and cust_id = cid)
where ac_tras = ctras
and exists (
select cust_addr from customer_address
where pr_adr = 'Y' and cust_id = cid)
;
在 exists
子句中使用哪个列名并不重要;有些人更喜欢使用 select *
或 select null
但这似乎真的是一个品味问题(除非你指定一个你以后不会使用的列并且不能从您正在使用的索引,这可能会强制执行不必要的 table 行查找)。
您也可以进行合并。 And has been pointed out several times now,您不需要光标或任何 PL/SQL 来执行此操作。