Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a column values from 'male' to 'female' and 'female' to 'male'

I have one table, gender, in which only two entries are there, 'male' and 'female' number of rows with these two entries only. Now I want to write a procedure which replaces these two values and the output should be as below,

Input           Output

sex             sex
------------------------
male            female
female          male
female          male
male            female

I am creating a procedure, which gives me an error. I am using a cursor to fetch more than one row. I know that we can do it by using only one update statement, but I want to try like this.

declare
  v_gen gender%rowtype;
  cursor cur_gender is
    select * from gender;
begin
  open cur_gender;
  loop
    fetch cur_gender into v_gen;
    select * from gender;
    if v_gen='male'
    then
      update gender set sex='female';
    else
      update gender set sex='male';
    end if;
    exit when v_gen%notfound;
  end loop;
  close cur_gender;
end;
like image 980
user1334522_Bhavin Avatar asked Jul 31 '13 11:07

user1334522_Bhavin


2 Answers

update Table1 set "col" = (case "col" when 'male' then 'female'
else 'male' end);

fiddle

like image 105
Praveen Prasannan Avatar answered Nov 03 '22 23:11

Praveen Prasannan


ID   Username   Email              Gender
1    sanjay     [email protected]   Male
2    nikky      [email protected]    Male
11   raj        [email protected]      Female
12   Rahul      [email protected]    Female
update users set gender = (case when gender = 'Male' then 'Female' else 'Male' end);
like image 45
Sanjay Verma Avatar answered Nov 03 '22 23:11

Sanjay Verma