2011-04-13 64 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++