设计资料表中的字段必须有的ID和ParentID 他们的关系是自身引用。
下面以 TableName(ID INT,ParentID INT) 表来做事例
- IF object_id('rTableNameByParentID') IS NOT NULL
- DROP PROCEDURE rTableNameByParentID
- GO
- CREATE PROCEDURE rTableNameByParentID
- @ParentID int ,
- @HasParent bit =0
- AS
- BEGIN
- SET NOCOUNT ON
- DECLARE @TypeID TABLE(ID INT)
- ;With CTE_TableNameID AS
- (
- SELECT ID FROM TableName WHERE ParentID=@ParentID
- UNION ALL
- SELECT a.ID FROM (SELECT *FROM TableName ) AS a INNER JOIN CTE_TableNameID AS b ON a.ParentID=b.ID
- )
- INSERT INTO @TypeID SELECT ID FROM CTE_TableNameID
- IF (@HasParent<>0)
- BEGIN
- INSERT INTO @TypeID SELECT ID FROM TableName WHERE ID=@ParentID
- END
- SELECT ID,ParentID FROM TableName WHERE ID IN(SELECT ID FROM @TypeID)
- END