Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Could someone be kind enough to help with query?

Author  Topic 

JBelthoff
Posting Yak Master

173 Posts

Posted - 2009-12-17 : 13:03:03
Hi,

I have a table of messages. Each row has an ID and a Parent ID. I would like to query this table so that I can pass in the MessageID and get a list starting with that message amd all of the replies to that message in descending order.

So for messageid 12070 I would want a result set like this:

messageid parentid frommemberid tomemberid subject
12070 12067 217124 260132 RE: RE: this is a message
12067 12043 260132 217124 RE: this is a message
12043 0 217124 260132 this is a message


Here is some sample data to work with and many thanks for your help!

Create Table #MyTemp
(
messageid bigint
,parentid bigint
,frommemberid bigint
,tomemberid bigint
,subject varchar(200)
)

Insert Into #MyTemp (messageid, parentid, frommemberid, tomemberid, subject) Values(12070, 12067, 217124, 260132, 'RE: RE: this is a message')
Insert Into #MyTemp (messageid, parentid, frommemberid, tomemberid, subject) Values(12067, 12043, 260132, 217124, 'RE: this is a message')
Insert Into #MyTemp (messageid, parentid, frommemberid, tomemberid, subject) Values(12043, 0, 217124, 260132, 'this is a message')
Insert Into #MyTemp (messageid, parentid, frommemberid, tomemberid, subject) Values(2902, 120, 8456, 9541, 'Hey Yo~!')
Insert Into #MyTemp (messageid, parentid, frommemberid, tomemberid, subject) Values(9920, 16, 98456, 35124, 'Check this out')

Select *
From #MyTemp

Drop Table #MyTemp





JBelthoff
• Hosts Station is a Professional Asp Hosting Provider
› As far as myself... I do this for fun!

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2009-12-17 : 13:16:52
[code]; with t1 as (select * from #MyTemp where messageid = 12070
union all select a.* from #MyTemp a inner join t1 b on a.messageid = b.parentid)
select * from t1[/code]

Ryan Randall - Yak of all trades
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page

JBelthoff
Posting Yak Master

173 Posts

Posted - 2009-12-17 : 13:32:05
Awesome Thank you!

JBelthoff
› As far as myself... I do this for fun!
Go to Top of Page
   

- Advertisement -