数据库访问控件:递归 逻辑优化 望指教
实现思路:每调用一次递归函数,就查询一条记录并添加到treeview中(之前是把数据全查出来然后再递归)
相关数据仍是之前用到的数据结构
void __fastcall TForm1::AddTree(AnsiString parentID,TTreeNode *Node){ SQLQuery1->SQL->Text= "select a.PDMObject_ID as Id, \ ISNULL(b.PDMObject_ID_Parent,0) as pId, a.User_ID, a.User_Name \ from PDM_Users_Roles_ORG a left join \ Pdm_Organization_tree b on a.PDMObject_ID=b.PDMObject_ID_Son \ where a.PDMObject_ID in \ (select distinct PDMObject_ID_Son as id from PDM_Organization_Tree \ union \ select distinct PDMObject_ID_Parent as id from PDM_Organization_Tree) \ and a.PDMObject_ID="+parentID; SQLQuery1->Open(); for(SQLQuery1->First();!SQLQuery1->Eof;SQLQuery1->Next()) { int Id,pId; Id = SQLQuery1->FieldByName("Id")->AsInteger; AnsiString text; text.sprintf("%d(%s %s)",Id, SQLQuery1->FieldByName("User_ID")->AsString, SQLQuery1->FieldByName("User_Name")->AsString ); TTreeNode *temp_Node; //临时节点 if((int)Node->Data == parentID) //若 == 则为父节点 { for(int i = 0;i<TreeView1->Items->Count;i++ ) //遍历树 { if( (int)TreeView1->Items->Item[i]->Data == parentID) temp_Node = TreeView1->Items->Item[i]; //指向父节点 } Node = temp_Node; } temp_Node = TreeView1->Items->AddChild(Node,text); temp_Node->Data = (void*)Id; AddTree(SQLQuery1->FieldByName("pId")->AsString,Node); }}
void __fastcall TForm1::AddTree(AnsiString parentID,TTreeNode *Node){ SQLQuery1->SQL->Text= "select a.PDMObject_ID as Id, \ ISNULL(b.PDMObject_ID_Parent,0) as pId, a.User_ID, a.User_Name \ from PDM_Users_Roles_ORG a left join \ Pdm_Organization_tree b on a.PDMObject_ID=b.PDMObject_ID_Son \ where a.PDMObject_ID in \ (select distinct PDMObject_ID_Son as id from PDM_Organization_Tree \ union \ select distinct PDMObject_ID_Parent as id from PDM_Organization_Tree) \ and pId ="+parentID; SQLQuery1->Open(); for(SQLQuery1->First();!SQLQuery1->Eof;SQLQuery1->Next()) { int Id,pId; Id = SQLQuery1->FieldByName("Id")->AsInteger; AnsiString text; text.sprintf("%d(%s %s)",Id, SQLQuery1->FieldByName("User_ID")->AsString, SQLQuery1->FieldByName("User_Name")->AsString ); TTreeNode *temp_Node; //临时节点 if(Node && (int)Node->Data == parentID) //若 == 则为父节点 { for(int i = 0;i<TreeView1->Items->Count;i++ ) //遍历树 { if( (int)TreeView1->Items->Item[i]->Data == parentID) temp_Node = TreeView1->Items->Item[i]; //指向父节点 } Node = temp_Node; } temp_Node = TreeView1->Items->AddChild(Node,text); temp_Node->Data = (void*)Id; AddTree(SQLQuery1->FieldByName("pId")->AsString,Node); }}
------解决方案--------------------
SQLQuery1->SQL->Text = .... ;
SQLQuery1->Open();
for(SQLQuery1->First();!SQLQuery1->Eof;SQLQuery1->Next())
{
.....\\Find ParentNode
temp_Node = TreeView1->Items->AddChild(Node,text);
...
AddTree(SQLQuery1->FieldByName("pId")->AsString,Node);//这里递归?
}
//这样是不行的吧。。。SQLQuery1作为全局数据,如何遍历记录集?
"每调用一次递归函数,就查询一条记录",如果是确认只查询回一条记录,又何必 for ...