表aaa中有一个字段是bbbsql="select * from [aaa] order by [bbb] asc"
问题:bbb字段是一串固定格式的文本。比如bbb字段内容是12,343,23,523,234,328中间是用英文逗号分隔开的!
请问如何用里面其中一个来排序。???比如我想用12这项或523这项来排序。这种排序如何才能实现!因为像这样的我写在一个字段里的。分开写的话好排序。就是要多5个字段。有什么好的方法吗?
有人说用sql="select * from [aaa] order by split(bbb,",")(0) asc"这种方式。但我测试时显示语句未结束。经过修改后。显示下标越界。请高手帮帮忙
------解决方案--------------------
先把字段拆分,再排序
------解决方案--------------------
--创建示例数据
create table #TA(a varchar(500))
insert into #TA select '12,343,21,523,234,328'
insert into #TA select '12,343,23,523,234,328'
insert into #TA select '12,343,22,523,234,328'
insert into #TA select '12,343,24,523,234,328'
--解决方案,函数脚本在下面
select * from #TA order by dbo.getstrofindex(a,3,',')
/* a
------------------------
12,343,21,523,234,328
12,343,22,523,234,328
12,343,23,523,234,328
12,343,24,523,234,328
(4 行受影响)
*/
GO
-- 函数脚本
create function getstrofindex (@str varchar(8000),@index int =0,@split Nvarchar(5))
returns varchar(8000)
as
begin
declare @str_return varchar(8000)
declare @start int
declare @next int
declare @location int
select @start =1
select @next =1 --如果习惯从0开始则select @next =0
select @location = charindex(@split,@str,@start)
while (@location <>0 and @index > @next )
begin
select @start = @location +1
select @location = charindex(@split,@str,@start)
select @next =@next +1
end
if @location =0 select @location =len(@str)+1 --如果是因为没有逗号退出,则认为逗号在字符串后
select @str_return = substring(@str,@start,@location -@start) --@start肯定是逗号之后的位置或者就是初始值1
if (@index <> @next ) select @str_return = '' --如果二者不相等,则是因为逗号太少,或者@index小于@next的初始值1。
return @str_return
end
------解决方案--------------------
select * from [aaa] order by split(bbb,",")(0) asc
方法应该是可行的,只是split这不是SQL内置函数,你需要自己创建,如何创建请参考:
http://blog.csdn.net/weiyao11/article/details/7496321
------解决方案--------------------
sql2005有xml的语法,可以拆分为多行
再按某行排序