Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
how can I change the data using a single query? I've created one table with columns ID and Gender. I've inserted values and now want to interchange the gender values. What was 'M' shall become 'F' and what was 'F' shall become 'M'.

Id Gender
1 M
2 F
3 M
4 F
5 M
6 F

AFTER CHANGE OUT PUT USE SINGLE QUERY
Id Gender
1 F
2 M
3 F
4 M
5 F
6 M

Thanks for your time!
Posted
Updated 5-Oct-11 22:48pm
v3
Comments
Manfred Rudolf Bihy 6-Oct-11 4:46am    
Edit: Moved question enhancements from repost to here (original). Spelling, grammar, clarity.

You can use the CASE WHEN construct to do the same: http://msdn.microsoft.com/en-us/library/ms181765(v=SQL.90).aspx[^].

An example:
SQL
UPDATE dbo.GenderTable
SET gender = (CASE
                  WHEN 'F' THEN 'M'
                  WHEN 'M' THEN 'F'
              END)


This works for SQL-Server 2005 & 2008.


Regards,

—MRB
 
Share this answer
 
v2
Comments
Espen Harlinn 6-Oct-11 4:59am    
Nice and simple, my 5
Theingi Win 6-Oct-11 5:10am    
I check your query in SQL-Server 2005. I found error.Should be like that
UPDATE dbo.GenderTable
SET gender = (CASE gender WHEN 'F' THEN 'M' WHEN 'M' THEN 'F' END )
Right?
Manfred Rudolf Bihy 6-Oct-11 7:11am    
If the query works for you that way in SQL-Server 2005, I guess you're right then.
I just reconsultet the T-SQL documentation on MSDN and on Technet and you're indeed right. The expression has to be in parenthesis here.
Thank you for pointing this out.
Have a look at this Swap values in 2 rows SQL[^] and try applying it to your situation.
 
Share this answer
 
Via a SQL update statement.

Check here:
http://www.w3schools.com/sql/sql_update.asp[^]

Based on this you should write something similar:

SQL
UPDATE peoples
SET sex='F'
WHERE name='udaipal'


If you want to apply this on every single field, just don't use the WHERE clause.


Cheers!
 
Share this answer
 
Some approaches discussed here[^]. You might find something useful that you can use.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900