繁体   English   中英

Oracle-根据条件更新一列或另一列

[英]Oracle - Updating one column or another based on a condition

我想更新表中的一条记录,但根据条件,我将更新一列或另一列,但是我不希望有2条单独的语句,因为这些语句很长且很详细。

这是过于简单的基本思想。

PROCEDURE Animal_something(p_updater VARCHAR2)

begin

  if p_updater = 'person' then   
    -- I want to update the modified_by  
  else   
    -- if p_updater = 'a process' I want to update modified_by_process

Update table_creatures
   set animal_type = 'Dog ,

**modified_by** = 'Bob'   
**or do this**  
**modified_by_process =** 'creature_package'

 where animal_legs = '4'

不要

if p_updater = 'person' then 
  Update table_creatures   
     set animal_type = 'Dog ,  
         modified_by = 'Bob'  
   where animal_legs = '4';  
else  

  Update table_creatures  
     set animal_type = 'Dog , 
         modified_by_process = 'creature_package'  
   where animal_legs = '4';

end;
UPDATE  table_creatures
SET     animal_type = 'Dog',
        modified_by = CASE p_updater WHEN 'person' THEN 'Bob' ELSE modified_by END,
        modified_by_process = CASE p_updater WHEN 'process' THEN 'creature_package' ELSE modified_by_process END
WHERE   animal_legs = 4

您可以使用动态SQL,例如:

PROCEDURE Animal_something(p_updater VARCHAR2)

  sql_string_pt1  VARCHAR2(2000) := 'UPDATE table_creatures SET animal_type = :1';
  sql_string_pt2  VARCHAR2(2000) := NULL;
  sql_string_pt3  VARCHAR2(2000) := ' WHERE animal_legs = :3';

begin

  if p_updater = 'person' then   
    sql_string_pt2 := ', modified_by = :2';
  else
    sql_string_pt2 := ', modified_by_process = :2';
  end if;

  EXECUTE IMMEDIATE sql_string_pt1 || sql_string_pt2 || sql_string_pt3
    USING 'Dog', 'Bob', '4';

end;

与Quassnoi的答案相比,这有两个优点:使用绑定变量,并且不需要在每次执行时都更新两列,即使实际值未更改,这也会生成重做。

不利的一面是,该语句在编译时根本未得到验证。

UPDATE  table_creatures 
SET     animal_type = 'Dog', 
        modified_by = DECODE(p_updater , 'person' , 'BOB' , 
                                         'proces' , 'creature_package' ,
                                         'GIVE DEFAULT VALUE')          
WHERE   animal_legs = 4;

你可以试试看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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