--思路,把字符串按.拆分,然后转换成int,再转换成varbinary拼接
Create Function f_Order(@SourceSql Varchar(8000),@StrSeprate Varchar(2))
Returns Varbinary(8000)
As
Begin
Declare @temp Varbinary(8000)=0x0
Declare @ch Varchar(100)
Set @SourceSql=@SourceSql+@StrSeprate
While(@SourceSql<>'')
Begin
Set @ch=left(@SourceSql,Charindex(@StrSeprate,@SourceSql,1)-1)
Set @temp=@temp+Convert(Varbinary, Convert(Int,@ch))
Set @SourceSql=Stuff(@SourceSql,1,Charindex(@StrSeprate,@SourceSql,1),'')
End
Return @temp
End
Go
--建表
Create table T
(
A Varchar(100)
)
--插入数据
Insert Into T Values('1.1')
Insert Into T Values('1.1.1')
Insert Into T Values('1.1.2')
Insert Into T Values('1.2')
Insert Into T Values('10.1')
Insert Into T Values('10.1.1')
Insert Into T Values('10.1.2')
Insert Into T Values('11.1')
Insert Into T Values('2.1')
Insert Into T Values('3.1')
Insert Into T Values('4.1')
--测试
Select * from T
order by dbo.f_Order(A,'.')
1:用ASCII码排序,DB2应该有这个函数吧,ASCII()?2:加个int类型的对照字段,'1'->1,'2'->2 ..'a'->97,'b'->98。
3:写个自定义函数也可以。
创建表:
create table test(str varchar(10))
insert into test values ('A1')
insert into test values ('A2')
insert into test values ('A10')
insert into test values ('A11')
insert into test values ('B1')
insert into test values ('B2')
insert into test values ('B10')
insert into test values ('B11')
执行:
select * from test order by left(str,1),convert(substr(str,2,length(str)-1),SIGNED)结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)