简体   繁体   中英

DB Error=ORA-01407: cannot update (“XXX”.“XXX”.“VALUE”) to NULL.

I have (simplified for this question) a table 'TAB' with two columns 'id' (integer and not null in db) and 'value' (varchar and not null in db). I am using a java application to update 'value' column for multiple rows in one go (which is my requirement). I have used update statement with case and when keyword. The query is being generated at runtime depending on number of rows modified.

The query works fine if data is updated for all rows together, but it gives me error when updated for less rows. Say we have three rows with id = 1, 2 and 3 with values A ,B and C resp.
When the query is fired for all three rows together then it works fine

UPDATE 
     TAB set value = CASE 
       WHEN id = 1 THEN 'X' WHEN id = 2 THEN 'Y' WHEN id = 3 THEN 'Z' 
END

But when the query is fired for less than three rows then I am encountering with a DB error.

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' END

Results in following error:

DB Error=ORA-01407: cannot update ("XXX"."XXX"."VALUE") to NULL.

I know this is happening because the 'value' column is not null in DB. I want to know whether the above query is trying to update all the remaining values with NULL?

The query works fine if I add ELSE part as written below.

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' ELSE TAB.value END

Will the above query impact any performance issue, if there are multiple rows in DB.

You are updating all the rows in the table. This is because you don't have a where clause.

To update one row add a where clause.

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' END where id = 1;

Or in your 3-row case,

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' WHEN id = 2 THEN 'Y'
WHEN id = 3 THEN 'Z' END where id in ( 1,2,3);

The way you are doing this is perfectly fine.

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' ELSE TAB.value END

other solution could be using where clause

UPDATE TAB set value = CASE WHEN id = 1 THEN 'X' when ID = 2 then 'Y' END where id in ( 1, 2 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM