试试这个工作正常:http ://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=101053
-- Structure
create table dbo.MyPeople (Id int, Name varchar(30), ParentId int)
-- Data
insert dbo.MyPeople
select 1, 'P1', null
union all select 2, 'P2', null
union all select 3, 'P1C1', 1
union all select 4, 'P1C2', 1
union all select 5, 'P2C1', 2
union all select 6, 'P1C2C1', 4
union all select 7, 'P1C1C1', 3
union all select 8, 'P1C1C1C1', 7
union all select 9, 'P2C1C1', 5
union all select 10, 'P1C3', 1
go
-- Function
create function dbo.AncestorPath(@Id int) returns varchar(100) as
begin
declare @Path varchar(100)
while 0 = 0
begin
select @Path = cast(Id as varchar(5)) + isnull('/' + @Path, ''), @Id = ParentId
from dbo.MyPeople where Id = @Id
if @@rowcount = 0 break
end
return @Path
end
go
-- Calculation
select * from (
select *, dbo.AncestorPath(Id) as AncestorPath from dbo.MyPeople) a
where '/' + AncestorPath + '/' like '%/1/%'
或者
尝试这样的递归过程
ALTER PROCEDURE dbo.GetChildren
@ParentId int
AS
SET NOCOUNT ON
SELECT *
FROM MainTable
WHERE ChildId IN
(
SELECT ParentId
FROM f_GetChildren(@ParentId)
UNION
SELECT ChildId
FROM f_GetChildren(@ParentId)
)
ORDER BY ParentId
SET NOCOUNT OFF
RETURN