BOOL CManageDataBase::GetDepTreeAllSons( int rootItem )
{
CADORecordset Rst(&m_DataBase);
BOOL bResult = FALSE;
CString strSQL;
int curItem = rootItem;
int level = 0;
try
{
strSQL.Format(_T("delete from Temp_DepSons"));
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
strSQL.Format(_T("delete from DepSons"));
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
level = 1;
strSQL.Format(_T("insert into Temp_DepSons values(%d,%d)"), curItem, level);
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
while (level > 0)
{
strSQL.Format(_T("select 1 from Temp_DepSons where levelson = %d"), level);
if (!Rst.Open((LPCTSTR)strSQL))
throw 0;
if (Rst.IsEOF())
{
--level;
continue;
}
strSQL.Format(_T("select top 1 item from Temp_DepSons where levelson = %d"), level);
if (!Rst.Open((LPCTSTR)strSQL))
throw 0;
if (!Rst.IsEOF())
{
Rst.GetFieldValue(0, curItem);
}
strSQL.Format(_T("delete from Temp_DepSons where item = %d"), curItem);
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
strSQL.Format(_T("insert into DepSons(id,parentid) select curno, parentno from Deptree where curno = %d"), curItem);
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
strSQL.Format(_T("insert into Temp_DepSons(item,levelson) select curno, %d from Deptree where parentno = %d"), level+1, curItem);
if(!m_DataBase.Execute((LPCTSTR)strSQL))
throw IDS_PROC_ERROR;
if (m_DataBase.GetRecordsAffected() > 0)
{
++level;
}
}
bResult = TRUE;
}
catch (int nID)
{
m_err.SetLastErrorDescription(nID);
}
return bResult;
}
//树型结构
CREATE TABLE `Deptree` (
`CURNO` INTEGER,
`PARENTNO` INTEGER,
`LAYER` BYTE
)
GO
//结果表
CREATE TABLE `DepSons` (
`id` INTEGER,
`parentid` INTEGER
)
GO
CREATE INDEX id ON DepSons(id)
GO
CREATE INDEX parentid ON DepSons(parentid)
GO
//中间表
CREATE TABLE `Temp_DepSons` (
`item` INTEGER,
`levelson` INTEGER
)
GO
CREATE INDEX id ON Temp_DepSons(item)
GO
CREATE INDEX levels ON Temp_DepSons(levelson)
GO
添加数据后的结构如下:
数据库数据如下:
如果是SQL Server 可以写个函数,这样:
CREATE FUNCTION [dbo].[GetDepTreeAllSons](@RootItem as int)
RETURNS @result TABLE ( id int, parentid int)
AS
BEGIN
declare @level int
declare @curItem int
declare @stack table( item int, level int )
set @curItem = @RootItem --根结点编号
set @level = 1
insert into @stack values( @curItem, @level )
while @level > 0
begin
if not exists( select 1 from @stack where level=@level )
begin
set @level = @level - 1
continue ;
end
select top 1 @curItem = item from @stack where level = @level
delete from @stack where item = @curItem
insert into @result select CURNO,PARENTNO from Deptree where CURNO = @curItem
insert into @stack select CURNO,@level+1 from Deptree where PARENTNO=@curItem
if @@rowcount > 0
set @level = @level + 1
end
--输入出结果
return
END