2

I have a table

EmpId   EmpName   ManagerId   Gender                  
1       Shahzad       2         M         
2       Santosh       1         F         
3       Sayanhi       2         M         

By mistake 'M' is assigned to female employees and 'F' is assigned to male employees. So I need to write a query to make the correction.

I tried the below query.

UPDATE Employee 
SET Gender='M' 
WHERE EmpId IN (SELECT EmpId FROM Employee WHERE Gender='F') 
  AND Gender='F'
WHERE EmpId IN (SELECT EmpId FROM Employee WHERE Gender='M')

but it didn't work.

1

3 Answers 3

9

here is a simple solution that will fix both cases at once:

UPDATE Employee
SET Gender = CASE Gender
  WHEN 'M' THEN 'F'
  WHEN 'F' THEN 'M'
END
Sign up to request clarification or add additional context in comments.

1 Comment

Yours is better :)
2

Try this instead:

SELECT   empid, empname, CASE WHEN gender = 'M' THEN 'F' ELSE 'M' END AS Gender
INTO     #tmp
FROM     Employee

If you're happy with what you see in there, then:

UPDATE    Employee
SET       Employee.Gender = #tmp.Gender
FROM      Employee
INNER JOIN #tmp
ON        Employee.empid = #tmp.empid

1 Comment

Sorry - qualified Employee.Gender - should work now.
1

If it's a given that every employee's gender is incorrect, and every gender is already M or F, why not:

UPDATE Employee
   SET Gender=(CASE WHEN Gender='F' 
                    THEN 'M' 
                    ELSE 'F' END)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.