读书人

比较复杂的【替换】有关问题来看看

发布时间: 2012-01-05 22:36:54 作者: rapoo

比较复杂的【替换】问题,高手进来看看。
一个表A:

id hy leftn rightn
1 101 0 102
2 102 103 0
3 103 113 112

查询leftn,匹配hy,如果hy中不存在 那么把hy中不存在的lefttn归零

如上图,应该把1、3归0

请问如何写改语句?

[解决办法]
create table a(id int,hy int ,leftn int,rightn int)
insert into a
select 1,101,0,102 union all
select 2,102,103,0 union all
select 3,103,113,112

update A
set leftn=case when exists(select 1 from A T where T.hy=A.leftn) then leftn else 0 end

select * from a
/*
id hy leftn rightn
----------- ----------- ----------- -----------
1 101 0 102
2 102 103 0
3 103 0 112
*/
drop table a
[解决办法]
那你就行下面句吧
update A
set leftn=case when exists(select 1 from A T where T.hy=A.leftn) then leftn else 0 end
[解决办法]
用这个!!

update hyclub
set rightnumber=case when exists(select 1 from hyclub T where ltrim(T.hynumber)=ltrim(hyclub.rightnumber)) then rightnumber else 0 end

读书人网 >SQL Server

热点推荐