Pregunta

I have a Table as below:

TABLE_1
{
Name varchar2(30)
Value_a number
Update_time timestamp
}

I want to conditionally update the value of update_time during the INSERT + MERGE depending on the value of "value_a". if value_a is less than 0.1, then check if update_time is null. if yes then update else don't. if value_a is greater than 0.1, then check if update_time is not null. if yes then make null.

I have a table_1_stage which I clear, then I insert all the data and then "merge or insert" in table_1 depending on the key match. I am using oracle 11g.

My Prepared Statement looks like the following: " MERGE INTO " + TABLE_1 + " TABLE1 " + " USING TABLE_1_STAGE TABLE1S " + " ON (TABLE1.NAME = TABLE1S.NAME ) " + " WHEN MATCHED THEN " + " UPDATE set VALUE_A = TABLE1S.VALUE_A " + " WHEN NOT MATCHED THEN " + " INSERT ( NAME, VALUE_A) " + " VALUES (?, ?) "

The update_time column is new and i need to set/reset it depending on the value_a.

i know a stored procedure might be a better call but i was looking if something can be done in the insert query to perform this?

¿Fue útil?

Solución

Update table1 
set Update_time = (case when value_a < 0.1 and Update_time is null then sysdate
                        when value_a > 0.1 and Update_time is not null then null
                   else Update_time end);

Change sysdate to your desired value.

EDIT:

Include Edit in the merge statement. See the below query (not tested with the real data) In this way we do not run the update on entire table.

Merge into table1 t1
using table1_staging t1s
on t1.name = t1s.name
when matched then
update t1.value_a = t1s.value_a,
t1.Update_time = (case when t1s.value_a < 0.1 and t1.Update_time is null then sysdate
                            when t1s.value_a > 0.1 and t1.Update_time is not null then null
                       else t1.Update_time end)
when not matched then
INSERT (name, values_a)
    VALUES (t1s.name, t1s.values_a);

Otros consejos

Your logic fits very well into an update statement. I think this is what you want:

update table1
    set update_time = sysdate
    where update_time is null and value_a < 0.1 or
          update_time is not null and value_a > 0.1;

You don't say what value you want to set update_time to. I assume it is the current time.

my solution eliminates updating whole table which could have poor performance depending on your data:

update table1 set update_time = (
select case when value_a > 0.1 and update_time is not null then null when value_a < 0.1 and update_time is null then sysdate) where update_time is null and value_a < 0.1 or update_time is not null and value_a > 0.1;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top