如何在oracle中添加或减去列中的值

时间:2017-01-18 10:30:30

标签: oracle sql-update

我正在尝试创建一个更新oracle过程,在更改完成后更新列。

Mass  |  SLAB   |  Mass Decreased/Increase
1100  | 200     |   100  // mass increased by 100
1000  | 200     | -100  // mass decrased by 100

我有上表,当对质量柱进行任何更改时,原始质量和已经改变的质量之间的差异被存储到质量减少/增加列中,它是正值或负值。我需要减去或将我的质量减少/增加的值添加到Slab列。我不知道如何检测质量是否减少或增加。你可以使用If语句吗?

例如,如果它增加

slab = 200 + 100

如果减少

slab =200-100

这就是我所拥有的

    procedure update_table(massNew number) 

 is

 begin 

        update
             Table t1
        set
             t1.Mass =massNew,

             t1.Mass Decreased/Increase= massNew - t1.Mass,
             t1.slab=t1.slab - (massNew - t1.Mass) // i added it to minus from the slab if there is a decrease but how to i set it to automatically detect if its a positive/negative number

        where code in ( select ct.description
        from codeTable  ct
        where ct.code=code
        );             
        commit;

2 个答案:

答案 0 :(得分:1)

以下更新似乎可以执行您想要的操作,但我不知道表中哪条记录实际应用更新的条件。

UPDATE table t1
SET    t1.mass   = in_mass,
   t1.slab      =
      CASE
         WHEN (t1.mass < in_mass) THEN t1.slab + (in_mass - t1.mass)
         WHEN (t1.mass > in_mass) THEN t1.slab - (t1.mass - in_mass)
         ELSE t1.slab
      END,
   t1.description      =
      CASE
         WHEN (t1.mass < in_mass) THEN in_mass - t1.mass || ' mass increase by ' || ABS (in_mass - t1.mass)
         WHEN (t1.mass > in_mass) THEN in_mass - t1.mass || ' mass decrease by ' || ABS (in_mass - t1.mass)
         ELSE 'No change'
      END;

编辑:包括测试程序。

CREATE OR REPLACE PROCEDURE mass_test_proc (in_mass IN NUMBER)
IS
BEGIN
UPDATE mass_test_table t1
SET    t1.mass   = in_mass,
       t1.slab   =
            CASE
              WHEN (t1.mass < in_mass) THEN t1.slab + (in_mass - t1.mass)
              WHEN (t1.mass > in_mass) THEN t1.slab - (t1.mass - in_mass)
              ELSE t1.slab
            END,
       t1.description      =
            CASE
              WHEN (t1.mass < in_mass) THEN in_mass - t1.mass || ' mass increase by ' || ABS (in_mass - t1.mass)
              WHEN (t1.mass > in_mass) THEN in_mass - t1.mass || ' mass decrease by ' || ABS (in_mass - t1.mass)
              ELSE 'No change'
            END;

COMMIT;

EXCEPTION
WHEN OTHERS THEN
  DBMS_OUTPUT.PUT_LINE('Error - '||sqlcode);
  DBMS_OUTPUT.PUT_LINE('MSG - '||substr(sqlerrm,1,64));
END; 

答案 1 :(得分:-1)

您可以尝试使用 案例表达

http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm

e.g:

for i, row in enumerate(self.result):
    if i > 0 and i % 10 == 0:
        input("Hit enter to show more")
    print row