Wednesday, 14 April 2010

Multiple row update from select

Whenever I have to do a multi row update from a select statement in Oracle I always come back to this bit of code from the good people at psoug.org who show you how it should always be done, it's not as simple as it might seem on the surface. If you don't do it correctly you end up updating all of the records in the table, some potentially with null data.
UPDATE test t
SET (tablespace_name, extent_management) = (
SELECT DISTINCT (u.tablespace_name, u.extent_management)
FROM user_tables a, user_tablespaces u
WHERE t.table_name = a.table_name
AND a.tablespace_name = u.tablespace_name)
WHERE t.table_name LIKE '%A%';
You can see their full low down on updates here: http://psoug.org/reference/update.html

No comments: