sql server 树形结构的创建
需要用到树形结构,在看了http://www.cnblogs.com/zplutor/archive/2009/07/31/1536146.html,原作只说了大概思路,让人费解,下面用比较清晰的过程描述下:
表结构:
lib_items:
ALTER PROCEDURE [dbo].[sp_items_level_test]@versionIdvarchar(30)ASBEGINDECLARE @item_id varchar(20), @Level int;SET @Level = 0CREATE TABLE #TreeViewTemp( item_id varchar(20) NOT NULL, desc nvarchar(500) NOT NULL, parent_id varchar(20) NULL, [Level] int NOT NULL)CREATE TABLE #TreeViewResult( item_id varchar(20) NOT NULL, desc nvarchar(500) NOT NULL)INSERT #TreeViewTempSELECT item_id, desc, parent_id, @LevelFROM lib_itemsWHERE parent_id = '' and version_id = @versionIdWHILE EXISTS (SELECT item_id FROM #TreeViewTemp)BEGIN SELECT TOP(1) @item_id = item_id FROM #TreeViewTemp WHERE [Level] = @Level ORDER BY item_id IF @@ROWCOUNT = 0 BEGIN SET @Level = @Level - 1 CONTINUE END INSERT #TreeViewResult SELECT item_id, SPACE(4 * @Level) + desc0 FROM #TreeViewTemp WHERE item_id = @item_id INSERT #TreeViewTemp SELECT item_id, desc, parent_id, @Level + 1 FROM lib_items WHERE parent_id = @item_id and version_id = @versionId IF @@ROWCOUNT <> 0 SET @Level = @Level + 1 DELETE #TreeViewTemp WHERE item_id = @item_idENDSELECT item_id, desc0 FROM #TreeViewResultDROP TABLE #TreeViewTempDROP TABLE #TreeViewResultEND