首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

急求取字符串?该如何处理

2012-04-24 
急:求取字符串?某个TABLE的字段里有这样的字符串值:ct_nameid-----------------------------------上海:30

急:求取字符串?
某个TABLE的字段里有这样的字符串值:

ct_name                                       id
-----------------------------------
上海:30/北京:60/                       1
上海:120/南京:60/                     2
北京:60/深圳:50/                       3
上海:100/杭州:90/                     4
上海:130/昆明:140/                   5

我现在想查询出   '上海 '的价格值,   并转换成数字按照升序排序.

谢谢各位帮忙!

[解决办法]

create table #t(ct_name varchar(100),id int)

insert into #t
select '上海:30/北京:60/ ', 1 union all
select '南京:60/上海:120/ ',2 union all
select '北京:60/深圳:50/ ', 3 union all
select '杭州:90/上海:100/ ',4 union all
select '上海:130/昆明:140/ ',5


select ct_name,
cast(case when charindex( '/ ',n1)> 0 then substring(n1,4,len(n1)-charindex( '/ ',n1)-3) else substring(n1,4,len(n1)-3) end as int) as n2
from
(
select ct_name,
substring(ct_name,charindex( '上海 ',ct_name),len(ct_name)-charindex( '上海 ',ct_name)) as n1
from #t
where charindex( '上海 ',ct_name)> 0
) t
order by n2


drop table #t

/*

--查询结果

ct_name n2
--------------------------------
上海:30/北京:60/ 30
杭州:90/上海:100/ 100
南京:60/上海:120/ 120
上海:130/昆明:140/ 130


*/

[解决办法]
select ct_name,
cast(case when charindex( '/ ',n1)> 0 then substring(n1,4,len(n1)- charindex( '/ ',n1)-3)else
substring(n1,4,len(n1)-3) end as int) as n2
from
(
select ct_name,
substring(ct_name,charindex( '上海 ',ct_name),len(ct_name)-charindex( '上海 ',ct_name)) as n1
from #t
where charindex( '上海 ',ct_name)> 0
) t

热点排行