Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Team,

I have a table....Unit Master(IN SQL 2005)
Unit_id Unit Link_id
1 Kg 2
2 gm 3
3 mg 0
4 DZN 5
5 Pcs 0



in output i need all the rows come in the output if they have link in any way parent to child or child to parent through a single query...is there any way to achieve in a single query ?

Output if pass in a proc parameter 1/2/3
Unit_id Unit Link_id
1 Kg 2
2 gm 3
3 mg 0

Output if pass in a proc parameter 4/5

Unit_id Unit Link_id
4 DZN 5
5 Pcs 0

Thanks
Sukhen Dass
Posted

Try:
SQL
SELECT Unitid, UnitLink
FROM UnitMaster
WHERE Unitid IN (1,2,3)


More: IN (t-sql)[^]
 
Share this answer
 
Comments
sukhen dass 4-Apr-14 2:18am    
i will pass only one input mean i will pass single unit_id(For.exe USP_GET_LINK_UNITS(1) or USP_GET_LINK_UNITS(2) or USP_GET_LINK_UNITS(3)).. but it should return all link rows either child to parent or parent to child...thanks
Maciej Los 4-Apr-14 2:29am    
There is no relationship between data suach as parent to child and child to parent.
SQL
create table parents(unit_id bigint identity(1,1),unit nvarchar(max),link_id bigint)
insert into parents values('kg',2)
insert into parents values('gm',3)
insert into parents values('mg',0)
insert into parents values('DZN',5)
insert into parents values('pcs',0)



just pass the parent_id :

SQL
with cte (link_id,unit_id,unit)
as
(
select link_id,unit_id,unit from parents where unit_id=1
union all
select b.link_id,b.unit_id,b.unit from cte as a inner join  parents  as b on a.link_id=b.unit_id
)
select unit_id,link_id,unit From cte


SQL
with cte (link_id,unit_id,unit)
as
(
select link_id,unit_id,unit from parents where unit_id=4
union all
select b.link_id,b.unit_id,b.unit from cte as a inner join  parents  as b on a.link_id=b.unit_id
)
select unit_id,link_id,unit From cte



Read this
 
Share this answer
 
Comments
sukhen dass 4-Apr-14 4:00am    
thanks--your solution is correct if its parent_id but i want if i pass any link_id/unit id it should return all rows parent to child/child to parent data vice a versa in a single query

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900