查询时,记录父子排序问题?
表中的记录按类分为父子关系,子的parentid为父的Rowid,父记录的parentid为空
结构如下:
行号 标题 城市 国家 时间 父子关系
---------------------------
1 测试1 深圳市 中国 2007-03-02
2 试测2 广州市 中国 2007-04-22
3 测试1子1 南山区 2007-03-25 1
4 测试2子1 海珠区 2007-04-30 2
5 测试1子2 宝安区 2007-05-03 1
6 测试3 北京市 中国 2006-05-30
7 测试2子2 越秀区 2007-04-29 2
8 测试1子3 罗湖区 2007-04-22 1
9 测试3子1 宣武区 2006-12-22 3
..............................
标题不一样
查询父级按时间倒序,每个父级后跟子记录,子记录按时间正序,谢谢!
[解决办法]
create function get_a_n(@id int)
returns varchar(32) as
begin
declare @r_id int,@dep int,@i int
select @dep=100,@i=1,@r_id=@id
while exists(select * from 表名 where 行号=@id and isnull(父子关系,0) <> 0)
select @i=@i*@dep,@id=父子关系,@r_id=@r_id+@id*@i from 表名 where 行号=@id and isnull(父子关系,0) <> 0
return cast(@r_id as varchar(32))
end
go
--查询
select * from adress order by dbo.get_a_n(行号)
[解决办法]
id大的时间应该在后,所以没有处理
[解决办法]
笨方法:
create table test
( id int ,
title varchar(50),
city varchar(10),
country varchar(10),
t_time datetime,
parent_id int)
insert into test
select 1 , '測試1 ' , '深圳市 ', '中國 ', '2007-03-02 ',0 union all
select 2 , '測試2 ' , '廣州市 ', '中國 ', '2007-04-22 ',0 union all
select 3 , '測試1子1 ' , '南山 ', ' ', '2007-03-25 ', 1 union all
select 4 , '測試2子1 ' , '海珠 ', ' ', '2007-04-30 ', 2 union all
select 5 , '測試1子2 ' , '寶安 ', ' ', '2007-05-03 ', 1 union all
select 6, '測試3 ' , '北京市 ', '中國 ', '2006-05-30 ',0 union all
select 7, '測試2子2 ' , '越秀 ', ' ', '2007-04-29 ', 2 union all
select 8, '測試1子3 ' , '羅湖 ', ' ', '2007-04-22 ', 1 union all
select 9, '測試3子1 ' , '玄武 ', ' ', '2006-12-22 ', 3
create function fun_tree
(
@pid varchar(10)
)
returns varchar(8000)
as
begin
declare @id int
declare @row_cur cursor
declare @sql varchar(8000)
Set @row_cur=Cursor for select id from test where parent_id=@pid
Set @sql= ' '
open @row_cur
fetch next from @row_cur into @id
while @@fetch_status=0
begin
Set @sql=@sql+char(13)+ 'union all select * from test where id= '+Cast(@id as varchar(10))+dbo.fun_tree(@id)
fetch next from @row_cur into @id
end
close @row_cur
deallocate @row_cur
return @sql
end
-----------------------
Declare @strSql varchar(8000)
set @strSql= 'select * from test where 1=0 '+dbo.fun_tree( '0 ')
exec(@strSql)