I would like to make a single round trip to an MSSQL database to retrieve multiple tables. Each table relies in one way or another on the same somewhat expensive lookup, which will grab a bunch of IDs and handle pagination and very basic filtering. So I'm trying to move the expensive part out so it happens only once, and reuse its result set multiple times afterwards.
Below is a really stripped-down version of what I'm trying to do. The "primary query" is the expensive lookup that's common to the next other queries below it. The "first result set" should return what I want, as you would expect, but the "second result set" fails because the primary query is out of scope.
-- Primary query
WITH t(ItemId, Row) AS (
SELECT ItemId, ROW_NUMBER() OVER(ORDER BY DateCreated DESC) AS Row
FROM Items
)
-- First result set
SELECT *
FROM Items
INNER JOIN t ON Items.ItemId = t.ItemId
WHERE t.Row < 10
-- Second result set
SELECT *
FROM Photos
INNER JOIN ItemPhotos ON Photos.PhotoId = ItemPhotos.PhotoId
INNER JOIN t ON ItemPhotos.ItemId = t.ItemId
WHERE t.Row < 10
Is there a way to do this so that the second result set works?
I would like to avoid creating temp tables because, in my experience, there is almost always a cheaper alternative that I've just not learned yet. In this case, I'm not sure there's an alternative, but I'm hoping someone knows a way around it. (I'll test both of course.)
I know that in the example above you can probably return a single result set by doing an INNER JOIN
on the whole thing, but in my case it's not a workable solution as the result set would be massive.