UPDATE WITH CASE SQL

Asked

Viewed 9,144 times

5

Is there any way I can use more than one column of the same table in a case statement in an update? for example, I have this table with these 3 lines

create table produto2(
codigo int primary key,
categoria varchar(30),
valor number(7,2));

insert into produto2 values (1001,'A',7.55);
insert into produto2 values (1002,'B',5.95);
insert into produto2 values (1003,'C',3.45);

and I’m trying to use a case with the category and value column to increase the value by 5.10 and 15 percent when the category is A,B,C

 update produto2 set valor = case when categoria = 'A' then valor*(valor*5/100)
                             case when categoria = 'B' then valor*(valor*10/100)
                             case when categoria = 'B' then valor*(valor*15/100)
                             end; 

but I am not succeeding, only with a PL/SQL that I created, but as you can see it is much more work, I wanted to try to simplify only with the case.

declare
cursor c_prod is select * from produto;
v_prod c_prod%rowtype;
begin
open c_prod;
loop
fetch c_prod into v_prod;
exit when c_prod%notfound;
end loop;
close c_prod;
if v_prod.categoria = 'A' then
update produto set valor = valor+(valor*5/100) where categoria = 'A';
elsif v_prod.categoria = 'B' then
update produto set valor = valor+(valor*10/100) where categoria = 'B';
elsif v_prod.categoria = 'C' then
update produto set valor = valor+(valor*15/100) where categoria = 'C';
end if;
end;

but anyway, there’s some way?

  • update product2 set value = (case when category = 'A' then value*(value5/100) when category = 'B' then value(value10/100) when category = 'B' then value(value*15/100) Else end value);

1 answer

8

You have a syntax error in your Update, you should use only one case and each condition within a when block

update produto2
   set valor = case
                 when categoria = 'A' then
                  valor * (valor * 5 / 100)
                 when categoria = 'B' then
                  valor * (valor * 10 / 100)
                 when categoria = 'C' then
                  valor * (valor * 15 / 100)
               end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.