读书人

列值转换有关问题

发布时间: 2012-01-11 22:28:46 作者: rapoo

列值转换问题
转换表A列shou的列值(shou列是int类型列,长度为1,值为1,2,3,0四者之一),
按照从上到下的顺序,只能有以下情况:
--第一种
1
--第二种
1
2
--第三种
1
2
3
1 =》3后面接1
--第四种
1
2
3
0 =》3后面接0

--正题转换目的(转换到cc列中)
--第一种
1 转换为 1
--第二种
1 转换为 0
2 转换为 2
--第三种
1 转换为 0
2 转换为 0
3 转换为 3
1 =》3后面接1
--第四种
1 转换为 0
2 转换为 0
3 转换为 4
0 =》3后面接0

0不需要转换
---------------------------------------------
举例:
shou列 cc列
1 1
1 0
2 2
1 0
2 0
3 3
1 0
2 0
3 4
0 0


1 0
2 2

[解决办法]
如果表中有其他数据不能后移的话只能用临时表或增加字段的方法
我把两种方法都列出来
1、临时表,LZ给出的参考就是这种方法,不过他的update语句的效率比较差
select identity(int,1,1) as id,* into #tempA from A
update #tempA set cc=case when isnull(b.shou,1)=1 then #tempA.shou
when b.shou=0 and #tempA.shou=3 then 4 else 0 end
from #tempA left join #tempA b on #tempA.id=b.id-1
delete from A
insert into A select shou,cc from #tempA
select * from A

2、临时列,因为修改列需要go所以这个方法不怎么实用
alter table A add tempid int
go
declare @i int
set @i=0
update A set @i=@i+1,tempid=@i
update A set cc=case when isnull(b.shou,1)=1 then a.shou
when b.shou=0 and a.shou=3 then 4 else 0 end
from A left join A b on A.tempid=b.tempid-1
go
alter table A drop column tempid
select * from A

以上两种方法均经过实际数据测试

读书人网 >SQL Server

热点推荐