求一sql语句,有难度,谢谢!
有一表MyTable,中有一字段id(nvarchar),其值如下:
id
1
2
2-1
2-2
2-1-1
2-1-2
2-1-2-1
3
3-1-3-4
请问,如何把这些每条记录中的数分离出来,并且不要重复的,并按照顺序归类,比如在上述记录中,归好类后得到:
id1
1
2
3
id2
1
2
id3
1
2
3
id4
1
4
问题点数:50、回复次数:10Top
1 楼pengdali()回复于 2003-11-03 20:30:10 得分 40
如果都是个位数就用substring.
select left(id,1),substring(id,3,1),substring(id,5,1)...Top
2 楼pengdali()回复于 2003-11-03 20:32:34 得分 0
如果不是:
create function getstrofindex (@str varchar(8000),@index int =0)
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
select @location = charindex('-',@str,@start)
while (@location <>0 and @index > @next )
begin
select @start = @location +1
select @location = charindex('-',@str,@start)
select @next =@next +1
end
if @location =0 select @location =len(@str)+1
select @str_return = substring(@str,@start,@location -@start)
if (@index <> @next ) select @str_return = ''
return @str_return
end
go
--调用:
--id1:
select distinct dbo.getstrofindex('1-2-4',1) from 你的表
--id2:
select distinct dbo.getstrofindex('1-2-4',2) from 你的表
--id3:
select distinct dbo.getstrofindex('1-2-4',3) from 你的表Top
3 楼wei_gogo(最后一支烟)回复于 2003-11-03 20:43:00 得分 0
感谢,我先试试,不只是个位数Top
4 楼txlicenhe(马可)回复于 2003-11-03 20:46:33 得分 10
调用大力的:
1:
Select distinct dbo.getstrofindex(id,1) as id1 from myTable where dbo.getstrofindex(id,1) > ''
2:
Select distinct dbo.getstrofindex(id,2) as id2 from myTable where dbo.getstrofindex(id,2) > ''
3:
Select distinct dbo.getstrofindex(id,3) as id3 from myTable where dbo.getstrofindex(id,3) > ''
4:
Select distinct dbo.getstrofindex(id,4) as id4 from myTable where dbo.getstrofindex(id,4) > ''
Top
5 楼wei_gogo(最后一支烟)回复于 2003-11-03 20:50:17 得分 0
调用中的第一个参数是常数么?那么不是没有什么意义了吗Top
6 楼wei_gogo(最后一支烟)回复于 2003-11-03 20:51:50 得分 0
谢谢,如果把上面的语句写在程序中该怎么写?Top
7 楼pengdali()回复于 2003-11-03 20:59:07 得分 0
你改为你的列名呀。Top
8 楼pengdali()回复于 2003-11-03 20:59:31 得分 0
select distinct dbo.getstrofindex(列名,3) from 你的表Top
9 楼wei_gogo(最后一支烟)回复于 2003-11-03 21:11:11 得分 0
我试了一下,可以了,但是把上面的代码怎么放进程序里呢?
还有,如果创建2遍函数好象就要报错,这个函数是放在哪里的呢?是不是在程序里使用select distinct dbo.getstrofindex(列名,3) from 你的表 这个语句时先要在sql server2000中把这个函数建立好呢?Top
10 楼pengdali()回复于 2003-11-03 21:46:03 得分 0
对你先建立好过程,只要调用就可以了。
select distinct dbo.getstrofindex(列名,3) as 列名 from 你的表
select distinct dbo.getstrofindex(列名,2) as 列名 from 你的表
和调用普通的select语句一样。Top




