Oracle-仅在源不为null时更新列

use*_*907 1 sql oracle

我有一个在包装内动态生成的更新语句。

我需要更新的target_field2唯一时间source_field2NOT NULL,如果NULL保持target_field2原样。

希望对此有一个简单的答案。这是关注的动态部分:

                 ELSIF cur_field_to_update.FIELD_NAME = 'SOURCE_FIELD2'
                 THEN
                    v_update_values := 
                        v_update_values
                        || ', CASE WHEN NVL('''
                        || data_cur.IND_TYPE
                        || ''', NULL) <> ''D'' THEN NULL ELSE TO_NUMBER(NVL('
                        || cur_field_to_update.FIELD_NAME
                        || ','
                        || TARGET_FIELD2
                        || ')) END';
Run Code Online (Sandbox Code Playgroud)

最终看起来像..

UPDATE target_table 
SET (target_field1,target_field2) = 
(SELECT source_field1, 
CASE WHEN NVL('A',NULL) <> 'A' 
THEN NULL   
ELSE TO_NUMBER(NVL(source_field2,target_field2))
END 
FROM source_table);
Run Code Online (Sandbox Code Playgroud)

900*_*000 6

如果您需要无条件更新一个字段,而仅当新值不为null时才更新另一个字段,则可以在新值NVL()和旧值之间进行选择:

update your_table set
 target_1 = source_1,
 target_2 = NVL(source_2, target_2)
where ...
Run Code Online (Sandbox Code Playgroud)

如果从select语句更新,则可以执行以下操作:

update target_table set
  (target_1, target_2) = (
    select source_1, 
           (NVL(source_2, 
               (select target_2 from target_table tt
                where tt.target_key = key_value)))
  )
where target_key = key_value;
Run Code Online (Sandbox Code Playgroud)

假定这target_key是一个唯一键,因此我们要更新同一条记录。

如果您的逻辑更加复杂,则使用PL / SQL可能会更容易,而且出错的可能性也较小。