暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

When I update one table from another, lots of my data turns to nulls - what have I done wrong ?

2011-01-01
430

The Oracle (tm) Users' Co-Operative FAQ

When I update one table from another, lots of my data turns to nulls - what have I done wrong ?


Author's name: Jonathan Lewis

Author's Email: Jonathan@jlcomp.demon.co.uk

Date written: 1st Nov 2002

Oracle version(s): 7 - 9

When I update one table from another, I lose a lot of the existing date, the values change to nulls - what have I done wrong ?


The problem here is that you have probably written some SQL to update data, without remembering that sometimes the associated data may be missing. The code sample that shows this problem usually looks something like:

update tableX	tx
set colA = (
		select sum(colB)
		from	tableY	ty
		where	ty.ref_col = tx.ref_col
	)
;

But what will happen if there are no matching rows in TableY for a given row in TableX ? The subquery finds no data. You might expect this to result in Oracle returning the error "no data found". In fact Oracle simply returns a null value - so if colA originally held a value, it will disappear.

To circumvent this problem, the simplest change is to modify the query so that it reads - update table X if there is any data. You do this by adding a where clause (that looks very similar to the subquery) to restrict the update to those rows for which relevant data exist. For example:

update tableX	tx
set colA = (
	select sum(colB)
	from	tableY	ty
	where	ty.ref_col = tx.ref_col
	)
where exists (
	select	null
	from	tableY	ty
	where	ty.ref_col = tx.ref_col
)
;

Note - this is not the only SQL solution for this type of update - take a look, for example, at updatable join views, which are typically twice as efficient as this subquery method.


Further reading: N/A



最后修改时间:2020-04-16 15:11:55
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论