I'm confused by something. I'm using T-SQL and trying to optimize code that looks like this:
SELECT * FROM MyTable mt
LEFT JOIN
(SELECT * FROM Table1 t1
LEFT JOIN api.tableValuedFunc(@someArgs) tvf
on tvf.Key = t1.Key) firstJoin
on mt.Key = firstJoin.key
LEFT JOIN
(SELECT * FROM Table2 t2
LEFT JOIN api.tableValuedFunc(@someArgs) tvf
on tvf.Key = t2.Key) secondJoin
on mt.Key = secondJoin.key
by doing this:
declare @tvfResult TABLE ( ... some columns ... )
insert into @tvfResults SELECT * FROM api.tableValuedFunc(@someArgs);
SELECT * FROM MyTable mt
LEFT JOIN
(SELECT * FROM Table1 t1
LEFT JOIN @tvfResults tvf
on tvf.Key = t1.Key) firstJoin
on mt.Key = firstJoin.key
LEFT JOIN
(SELECT * FROM Table2 t2
LEFT JOIN @tvfResults tvf
on tvf.Key = t2.Key) secondJoin
on mt.Key = secondJoin.key
This doubles the time it takes to execute! Why is this? In the second example, I (naively) assume I'm executing the function half as often. Is there some kind of SQL wizardry happening behind the scenes that I'm ruining?