sql表中2行的交换值

时间:2011-04-13 06:21:58

标签: sql

我有一个有列名称课程的表。第二行是“C ++”,第四行是“ASP.net”。

我希望将其与更新查询的值互换。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用update更改值,例如:

update YourTable set Course = 'ASP.NET' where id = 2
update YourTable set Course = 'C++' where id = 4

或:

update  YourTable 
set     Course = 
        case id
        when 2 then 'ASP.NET'
        when 4 then 'C++'
        end 
where   id in (2,4)

答案 1 :(得分:0)

测试表和数据

create table YourTable(id int primary key, course varchar(10))

insert into  YourTable values (1, 'Delphi')
insert into  YourTable values (2, 'C++')
insert into  YourTable values (3, 'Clipper')
insert into  YourTable values (4, 'ASP.net')

更新到开关2和4

update YourTable set
  course = case id
             when 4 then (select course from YourTable where id = 2)
             when 2 then (select course from YourTable where id = 4)
             else T.course
           end  
from
  YourTable as T
where T.id in (2, 4)  

结果

id  course
1   Delphi
2   ASP.net
3   Clipper
4   C++