tags:

views:

100

answers:

3

I have a SQL table (MYSQL 4.0 to be precise) composed of the following :

int no (primary)
int field1
int field2

I would like to swap the values of field1 with the values of field2 and vice-versa.

Ex.: 1;2.5;3.76 becomes 1;3.76;2.5

I need a swapping temporary variable of some sort. But I don't think I can use something like

Set @var1 = field1

inside my update statement. And I don't think altering the table to add a temporary column is my best bet either.

+2  A: 

My initial thought was to try this:

UPDATE YourTable
   SET field1=field2
      ,field2=field1
   WHERE ...

SQL Server syntax here (but has worked this way in every database I've ever used, I've not used mysql):

declare @x table (field1 int, field2 int)
insert @x values (1,2)
update @x set field1=field2, field2=field1
select * from @x

OUTPUT

field1      field2
----------- -----------
2           1

(1 row(s) affected)

However after a little research, I came across this: http://stackoverflow.com/questions/37649/swapping-column-values-in-mysql/559291#559291

KM
This will not work as expected in mysql, there's a overview of UPDATE behaviours in one of the so questions, mysql and ather DBMS fail on this
Unreason
@Unreason, works fine in SQL Srver, but see the link in my edited answer.
KM
@KM, It works in oracle, postgres, db2 and I think SQLite as expected. It was mysql and another one failing... can't find the question now.
Unreason
Ok, found it http://stackoverflow.com/questions/2203202/sql-update-order-of-evaluation
Unreason
After testing it: doesn't work in mysql.
Silence
@Silence said `After testing it: doesn't work in mysql`. Duh, I said that the code was for SQL Server! The linked answer shows how to do this in mysql.
KM
+2  A: 

How about creating a work table, push the data there and the join with your current table?

Raj
+1 for a good idea.
Silence
+1  A: 

I found this

UPDATE swap_test 
SET x=(@temp:=x), 
    x = y, 
    y = @temp
WHERE ...

here as solution with session variables (there are other solutions in the provided link and also a link back to another so question)

Unreason
@Silence, yes you are right, no point in keeping the multi table version of the answer, the documentation at http://dev.mysql.com/doc/refman/5.1/en/update.html clearly states that the behaviour is not defined (although I'll run some tests now out of curiosity)
Unreason
Works. Easiest answer to implement. Thank you.
Silence