日期:2014-05-19  浏览次数:20487 次

急急:大家来顶一下把
某个TABLE的字段里有这样的字符串值:

ct_name                                       id
-----------------------------------
上海:30/北京:60/                       1
南京:60/上海:120/                     2
北京:60/深圳:50/                       3
杭州:90/上海:100/                     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


*/

------解决方案--------------------
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
go

select * from (
select ct_name,id,
jg=substring(ct_name,charindex( '上海: ',ct_name)+3,charindex( '/ ',ct_name,charindex( '上海: ',ct_name))-charindex( '上海: ',ct_name)-3)
from #t where charindex( '上海: ',ct_name) > 0) a
order by cast(jg as int)


drop table #t


/*

--查询结果

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

*/

------解决方案--------------------
^_^
由于LEN( '南京: ')=3 ,所以语句中就多次直接使用 +3或-3,在实际使用中你可以灵活调整