开发者

Interchange value of 2 row in sql table

I have a table which has column name course. In 2nd row course is "C++" and in 4th row course is "ASP.net".

I want to i开发者_如何学JAVAnterchange that to value with update query. How can I achieve this?


You can change the values with update, like:

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

or:

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


Test table and data

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

Update to switch 2 and 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)  

Result

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜