May 21, 2014 at 3:03 am
I need a help regarding this...
There is a table like this
PK Desc Reference_PK
-- ------- ------
1 Gautham NULL
2 Harsha NULL
3 Kamal 1
4 Sai 2
5 Rajesh 2
6 Pradeep 1
I want a select statement to display like...
1> If Reference_PK column is Null, then it should display desc.
2> If Reference_PK is having some value ,then it should display the desc of that number.
please help me with this..
Thanks.,
May 21, 2014 at 3:24 am
SELECT T1.*,ISNULL(T2.Desc,T1.Desc) AS YOUNEED
FROM [YOUTABLE] T1 LEFT JOIN [YOUTABLE] T2
ON T1.Reference_PK = T2.PK
May 21, 2014 at 3:36 am
Try this
create table #Parent
(
PK int primary key not null,
Descr varchar(10) not null,
Reference_PK int null
)
insert into #Parent
select 1, 'Gautham', null union all
select 2, 'Harsha', null union all
select 3, 'Kamal', 1 union all
select 4, 'Sai', 2 union all
select 5, 'Rajesh', 2 union all
select 6, 'Pradeep', 1
select
isnull(p.descr,p1.Descr)
from #Parent p
right join #Parent p1 on p1.Reference_PK = p.PK
drop table #Parent
How to post a question to get the most help http://www.sqlservercentral.com/articles/Best+Practices/61537
May 21, 2014 at 8:21 am
If you have more than one level, you could use a recursive CTE.
create table #Parent
(
PK int primary key not null,
Descr varchar(10) not null,
Reference_PK int null
);
insert into #Parent
select 1, 'Gautham', null union all
select 2, 'Harsha', null union all
select 3, 'Kamal', 1 union all
select 4, 'Sai', 2 union all
select 5, 'Rajesh', 2 union all
select 6, 'Pradeep', 1 union all
select 7, 'Someone', 5;
WITH rCTE AS(
SELECT PK, Descr, Reference_PK
FROM #Parent
UNION ALL
SELECT r.PK, p.Descr, p.Reference_PK
FROM #Parent p
JOIN rCTE r ON p.PK = r.Reference_PK
)
SELECT PK, Descr
FROM rCTE
WHERE Reference_PK IS NULL
ORDER BY PK;
GO
drop table #Parent;
May 21, 2014 at 5:50 pm
gautham.gn (5/21/2014)
I need a help regarding this...There is a table like this
PK Desc Reference_PK
-- ------- ------
1 Gautham NULL
2 Harsha NULL
3 Kamal 1
4 Sai 2
5 Rajesh 2
6 Pradeep 1
I want a select statement to display like...
1> If Reference_PK column is Null, then it should display desc.
2> If Reference_PK is having some value ,then it should display the desc of that number.
please help me with this..
Thanks.,
How many rows do you have in the real table? How often are they updated?
--Jeff Moden
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply