2011-04-13 95 views
0

我有一个有列名过程的表。第二排当然是“C++”,第四排当然是“ASP.net”。sql表中第2行的交换值

我想通过更新查询将其与值进行交换。我怎样才能做到这一点?

回答

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) 
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++