求一sql语句,有难度,谢谢!

wei_gogo 2003-11-03 08:26:16
有一表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
...全文
26 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-11-03
  • 打赏
  • 举报
回复
对你先建立好过程,只要调用就可以了。

select distinct dbo.getstrofindex(列名,3) as 列名 from 你的表

select distinct dbo.getstrofindex(列名,2) as 列名 from 你的表

和调用普通的select语句一样。
wei_gogo 2003-11-03
  • 打赏
  • 举报
回复
我试了一下,可以了,但是把上面的代码怎么放进程序里呢?
还有,如果创建2遍函数好象就要报错,这个函数是放在哪里的呢?是不是在程序里使用select distinct dbo.getstrofindex(列名,3) from 你的表 这个语句时先要在sql server2000中把这个函数建立好呢?
pengdali 2003-11-03
  • 打赏
  • 举报
回复
select distinct dbo.getstrofindex(列名,3) from 你的表
pengdali 2003-11-03
  • 打赏
  • 举报
回复
你改为你的列名呀。
wei_gogo 2003-11-03
  • 打赏
  • 举报
回复
谢谢,如果把上面的语句写在程序中该怎么写?
wei_gogo 2003-11-03
  • 打赏
  • 举报
回复
调用中的第一个参数是常数么?那么不是没有什么意义了吗
txlicenhe 2003-11-03
  • 打赏
  • 举报
回复
调用大力的:
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) > ''

wei_gogo 2003-11-03
  • 打赏
  • 举报
回复
感谢,我先试试,不只是个位数
pengdali 2003-11-03
  • 打赏
  • 举报
回复
如果不是:

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 你的表
pengdali 2003-11-03
  • 打赏
  • 举报
回复
如果都是个位数就用substring.
select left(id,1),substring(id,3,1),substring(id,5,1)...

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧