Return multiple result sets AND use result set 1 to filter result set 2

863 views Asked by At
/* result 1 */
 select Id, Name
 from Items


/* result 2 */
 select Id,
        Alias
 from ItemAliases
 where Id in (
     select Id, Name
     from table abc
 )

We use SQL Server 2008.

Using the above example, it should be pretty straightforward what I'm trying to do.

I need to return the results of query 1... and return the results of query 2.

Query 2 however, needs to filter to only include records from result 1.

Here is my attempt to show what I would like to end up with.

VAR A = (
   select Id, Name
   from Items
)

/* result 1 */
 select A.*

/* result 2 */
 select Id,
        Alias
 from ItemAliases
 where Id in ( A.Id )
2

There are 2 answers

0
nathan_jr On BEST ANSWER

I think you just want to store Result1 and use it to compose Result2:

declare @Result1 table (Id int primary key, Name varchar(100));

insert into @Result1
    -- store Result1
    select Id, Name
    from Items

--return Result1
select Id, Name 
from @Result1;


--return Result2 using stored Result1
select Id,
    Alias
from ItemAliases
where Id in (select Id from @Result1);
0
Jade On
--Result 1
SELECT  ID, Name
FROM    Items
[You WHERE Clause here if any]

--Result 2
SELECT Id, Alias
 FROM ItemAliases ia
        INNER JOIN Items i ON ia.ID = i.ID

OR

--Using temporay in memory table
DECLARE @abc AS TABLE (
ID AS Int,
Name AS varchar(25)
)

SELECT  ID, Name
INTO    @abc
FROM    Items
[You WHERE Clause here if any]

--Result 1
SELECT * FROM @abc

--Result 2
SELECT Id, Alias
 FROM ItemAliases ia
        INNER JOIN @abc i ON ia.ID = i.ID