我希望sql查询以
的形式输出 1.1.1,1.1.2,1.1.3...
我尝试了order by子句,但我的结果为1.1.1,1.1.10,1.1.11,1.1.2,1.1.3...
我的程序是:
select *
from Projects,
where iId in (select value
from ParmsToList(@projectid,',')
)
And Projects.categoryid > 0
order by Projects.vProjectName
答案 0 :(得分:4)
一种方法是使它们看起来像层次结构节点
;with t(f) as (
select '1.1.1' union
select '1.1.10' union
select '1.1.11' union
select '1.1.2' union
select '1.1.3'
)
select
*
from
t
order by
cast('/' + replace(f, '.', '/') + '/' as hierarchyid)
的
f
1.1.1
1.1.2
1.1.3
1.1.10
1.1.11
答案 1 :(得分:4)
SQL Server 2008 +:
select t.v
from (values ('1.1.1'), ('1.1.10'), ('1.1.11'), ('1.1.2'), ('1.1.3'), ('1.2.1'), ('10.1.1')) as t(v)
cross apply (
select x = cast('<i>' + replace(v, '.', '</i><i>') + '</i>' as xml)
) x
order by x.value('i[1]','int'),x.value('i[2]','int'), x.value('i[3]','int')
SQL Server 2005 +:
;with t(v) as (
select '1.1.1' union all
select '1.1.10' union all
select '1.1.11' union all
select '1.1.2' union all
select '1.1.3' union all
select '1.2.1' union all
select '10.1.1'
)
select t.v
from t
cross apply (
select x = cast('<i>' + replace(v, '.', '</i><i>') + '</i>' as xml)
) x
order by x.value('i[1]','int'),x.value('i[2]','int'), x.value('i[3]','int')
输出:
v
------
1.1.1
1.1.2
1.1.3
1.1.10
1.1.11
1.2.1
10.1.1
答案 2 :(得分:1)
试试这个:
ORDER BY PATINDEX('%.%', [fieldname])
它对我有用