在SQL Server表的列中交换值

Red*_*ddy 1 sql-server

我试图通过使用下面的查询交换我的表数据(1 => 3,2 => 1,3 => 2).

/* Temporarily set 1 to a dummy unused value of 11 
   so they are disambiguated from those set to 1 in the next step */
update <tablename> 
set id = 11
where id = 1

update <tablename> 
set id = 1
where id = 2

update <tablename> 
set id = 2
where id = 3

update <tablename> 
set id = 3
where id = 11
Run Code Online (Sandbox Code Playgroud)

想知道我是否可以优化我的脚本.

Mar*_*ith 6

你可以使用case.从概念上讲,操作"一次性"发生,因此不需要像顺序方法那样使用第四个虚拟值.

UPDATE YourTable
SET ID = CASE ID WHEN 1 THEN 3
                 WHEN 2 THEN 1
                 WHEN 3 THEN 2
         END
WHERE ID IN (1,2,3)
Run Code Online (Sandbox Code Playgroud)

虽然改变id是不寻常的,因为它们通常应该是不可改变的.