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)
 Select Based on Previous Results

Author  Topic 

cryan540
Starting Member

2 Posts

Posted - 2009-05-20 : 15:03:19
Is there any way to select from a previous result without storing the result in a Temp table or Table Variable?

For example (really basic select for example):

select id from [a] -> Result 1
select * from [b] where id in (selec id from [RESULT 1])

I know you can store the values in a Table Variable but I wanted to know if you can just select from the previous result.


Also, can you use a WITH statement with two selects. I can only use it in one select then I can not reuse it again. Any help would be appreciated.

Thank you.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-05-20 : 15:05:13
you can just use

select * from [b] where id in (select id from [a])

by with statement do you mean CTE? if yes then it can be used only once after definition in first query alone

Go to Top of Page

cryan540
Starting Member

2 Posts

Posted - 2009-05-20 : 15:18:48
Thank you for the quick reply. What I am asking for the select is more complex and I need to return both results.

For example (Still basic, but gives a better idea):

Query 1 - I need to return the results:

select a.id, .name from [tb1] as a
join [tb2] as b on a.id=b.id
where a.name like '%test%'

[b]Query 2 - I need to return the results:


select * from [tb3] where id in (select id from [QUERY 1])


I need to return the results to both queries but I do not want to have to execute Query 1 again to get Query 2. I just want to be able to do a select of the first result. These are quickly written queries just to give an example but you get the idea.

About the CTE, I thought so but I did not know if I was missing something.

Thank you for the help.
Go to Top of Page
   

- Advertisement -