---SQL2000---
--测试数据
CREATE TABLE dbo.tbtest(col1 int,col2 int)
INSERT dbo.tbtest SELECT 1,0
UNION ALL SELECT 2,1
UNION ALL SELECT 3,1
UNION ALL SELECT 4,2
UNION ALL SELECT 5,2
UNION ALL SELECT 6,2
UNION ALL SELECT 7,3
UNION ALL SELECT 8,3
UNION ALL SELECT 9,3
UNION ALL SELECT 10,7
--把这个表变为
/*
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 2
2 4
2 5
2 6
3 3
3 7
3 8
3 9
7 7
7 10
8 8
9 9
10 10
这种形式的数据
*/
--建立函数(此函数参考邹建大哥的)
alter function f_cid(
@id int
)returns @re table(col1 int,[level] int)
as
begin
declare @l int
set @l=0
insert @re select col1,@l from dbo.tbtest where col2=@id
while @@rowcount>0 --知道没有子插入为止
begin
set @l=@l+1
insert @re select a.col1,@l
from dbo.tbtest a,@re b
where a.col2=b.col1 and b.[level]=@l-1
end
return
end
go
IF object_id('tempdb..#BB') IS not null DROP TABLE #BB
CREATE table #BB(col1 int,col2 int)
DECLARE tnames_cursor CURSOR
FOR
SELECT col1 FROM tbtest ORDER BY col1
OPEN tnames_cursor
DECLARE @cur1 INT
FETCH NEXT FROM tnames_cursor INTO @cur1
WHILE(@@fetch_status=0)
BEGIN
-- print @cur1
-- select a.* from tbtest a,f_cid(1) b where a.col1=b.col1
INSERT #BB
SELECT a.col1,@cur1 FROM #aa a,f_cid(@cur1) b WHERE a.col1=b.col1
FETCH NEXT FROM tnames_cursor INTO @cur1
END
CLOSE tnames_cursor
DEALLOCATE tnames_cursor
SELECT re.*
FROM (
SELECT * FROM #bb --不包括自己的所有遍历
UNION
SELECT DISTINCT col1,col1 AS col2 FROM tbtest ) AS re
ORDER BY re.col2
IF object_id('tempdb..#BB') IS not null DROP TABLE #BB
posted on 2008-03-07 18:16
马强 阅读(214)
评论(0) 编辑 收藏 引用 所属分类:
SQL应用