I am working with an Oracle 10g Database.
I have the following two tables:
T_DEBTOR :
- ID_DEBTOR
- HEADER
T_ELEMENT :
- ID_ELEMENT
- ID_DEBTOR
- INSURER
These two tables are joined using the ID_DEBTOR field.
I want to update the T_ELEMENT.INSURER value with the associated T_DEBTOR.HEADER only if HEADER is not null.
In others words:
If T_DEBTOR.HEADER != null
Then T_ELEMENT.INSURER = T_DEBTOR.HEADER
Else T_ELEMENT.INSURER is not modified!
I tried to use the following SQL query:
update
T_ELEMENT elt
set elt.INSURER = (
select HEADER
from T_DEBTOR debtor
where
debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR);
This query is working for all elements linked to debtors that has a HEADER not null.
However, when the T_DEBTOR.HEADER is null, then this query set the T_ELEMENT.INSURER to null, which is not correct.
ie:
If T_DEBTOR.HEADER != null
Then T_ELEMENT.INSURER = T_DEBTOR.HEADER --> This part is OK
Else T_ELEMENT.INSURER is set to null --> This part is NOT OK
What is wrong with my query?
Edit, regarding the Brian Storrar answer:
What I want to do is something like that:
update
T_ELEMENT elt
set elt.INSURER = (
select HEADER
from T_DEBTOR debtor
where
debtor.HEADER is not null
and debtor.ID_DEBTOR = elt.ID_DEBTOR)
where debtor.HEADER is not null;
Good question.
To simulate your situation, I’ve created sample tables:
And with your current update statement, the problem becomes clear: the “not to be updated” values are set to NULL:
The best way to do this update, is to update a join of both tables. There are some restrictions however:
With the bypass ujvc hint, we can circumvent this restriction.
But it is not advisable to do so unless you know really really sure that t_debtor.id_debtor is unique.
It’s better to just add a primary key. You’ll probably have this one already in place:
Regards,
Rob.