hi, just want to post something that might be useful
see u
DECLARE @a AS TABLE(autoid INT, name VARCHAR(20), parentid INT)INSERT INTO @a (autoid, name, parentid)SELECT 1, '1', 0UNION ALLSELECT 2, '1.1', 1UNION ALLSELECT 3, '1.2', 1UNION ALLSELECT 4, '1.2.1', 3UNION ALLSELECT 5, '2.1', 2UNION ALLSELECT 6, '3.1', 3UNION ALLSELECT 7, '3.2', 3/*1 1 02 1.1 13 1.2 14 1.2.1 35 2.1 26 3.1 37 3.2 3*//*Get Parent Records from child '1.2.1'return:1.2 (parent from '1.2.1')1 (parent from '1.2')*/;WITH employeeMasterAS ( SELECT p.autoid ,p.parentid ,p.[name]FROM @a pWHERE p.[NAME] = '1.2.1'UNION ALLSELECT c.autoid ,c.parentid ,c.[name]FROM employeeMaster cteINNER JOIN @a c ON c.autoid = cte.parentid)SELECT *FROM employeeMaster mWHERE m.[name] <> '1.2.1'
/*Get Child Records from parent '1.2'return:1.2.13.13.2*/;WITH employeeMasterAS ( SELECT p.autoid ,p.parentid ,p.[name]FROM @a pWHERE p.[NAME] = '1.2'UNION ALLSELECT c.autoid ,c.parentid ,c.[name]FROM employeeMaster cteINNER JOIN @a c ON c.parentid = cte.autoid)SELECT *FROM employeeMaster mWHERE m.[name] <> '1.2'
see u
Comments