标签:递归 var empty 数据 child tree free 今天 query
本来我一直都是使用递归算法, 效率很低
下边这段代码是我原来写的
-----------------------------------------------------------------------------------------------------
procedure TForm1.GetDepartmentMsg;
var
Test, Test2 : TTreeNode;
procedure NodeAdd(Test : TTreeNode; DepartmentId : string);
var
Testlevel : TTreeNode;
TestQuery : TADOQuery;
begin
try
TestQuery := TADOQuery.Create(Nil);
TestQuery.Connection := ADOConnection1;
With TestQuery do
begin
Close;
SQL.Text := ‘Select DepartmentID ,NAME from Department where DepartmentID like ‘‘‘+DepartmentId+‘%‘‘ and Len(DepartmentId) = ‘ + IntToStr(Length (DepartmentId) + 2) + ‘Group by DepartmentID ,name order by DepartmentID ‘ ;
Open;
if Not IsEmpty then
begin
while not Eof do
begin
Testlevel := TreeView1.Items.AddChild(Test,TestQuery.fieldbyName(‘Name‘).AsString + ‘ | ‘+ TestQuery.fieldbyName(‘DepartmentId‘).AsString);
NodeAdd(Testlevel,TestQuery.fieldbyName(‘DepartmentId‘).AsString);
Testlevel.ImageIndex := Testlevel.Level -1;
Testlevel.SelectedIndex := Testlevel.Level -1;
Next;
end;
end;
end;
finally
TestQuery.free;
end;
end;
begin
Test := TreeView1.Items.Add(nil,‘ ***** | 00‘);
Test.ImageIndex := 1;
with Query1 do
begin
Close;
Sql.Text := ‘Select * from Department where State = ‘‘正常‘‘ and DepartmentLevel = ‘‘1‘‘ ‘;
Open;
end;
Query1.First;
TreeView1.Items.BeginUpdate;
while not Query1.Eof do
begin
Test2 := TreeView1.Items.AddChild(Test,Query1.fieldbyName(‘Name‘).AsString + ‘ | ‘+ Query1.fieldbyName(‘DepartmentId‘).AsString) ;
NodeAdd(Test2,Query1.fieldbyName(‘DepartmentId‘).AsString);
Query1.Next;
end;
TreeView1.Items.EndUpdate;
Query1.Close;
end;
今天无事测试了这段代码 时间是6-7秒左右
下边这段改进后的,不使用递归
procedure TForm1.NewGetDepartmentMsg;
const
DivNum = 2;
var
nLevel: Integer;
pNodes: array[0..1023] of TTreeNode;
DepartmentID, Name: string;
Str: string;
begin
Str := ‘Select DepartmentID, Name from Department order by DepartmentID‘;
with adoquery1 do
begin
Close;
Sql.clear;
Sql.add(Str);
Open;
end;
TreeView1.Items.Clear;
TreeView1.Items.BeginUpdate;
pNodes[0] := TreeView1.Items.Add(nil, ‘***‘);
if Not ADOQuery1.IsEmpty then
while not ADOQuery1.Eof do
begin
DepartmentID := ADOQuery1.fieldbyName(‘DepartmentID‘).AsString;
Name := ADOQuery1.fieldbyName(‘Name‘).AsString;
nLevel := Length(DepartmentID) div DivNum ;
pNodes[nLevel] := TreeView1.Items.AddChild(pNodes[nLevel - 1], DepartmentID + ‘ | ‘ + Name);
ADOQuery1.Next;
end;
TreeView1.Items.EndUpdate;
ADOQuery1.Close;
end;
这个算法主要合理利用了 ‘Select DepartmentID, Name from Department order by DepartmentID‘ 来排序, 这就保证了
pNodes[nLevel] := TreeView1.Items.AddChild(pNodes[nLevel - 1], DepartmentID + ‘ | ‘ + Name);
他的上级结点不为空
这段代码我一测试, 大概是0.2秒左右, 数据和上边那段代码处理一样的数据
这样写肯定是有缺陷的, 也不是什么情况下都能使用
写得不对的地方,欢迎批评和指正,谢谢
标签:递归 var empty 数据 child tree free 今天 query
原文地址:https://www.cnblogs.com/jijm123/p/11385687.html