Consider the following query:
create function unpivoter(@TableID int)
returns table
as
return
(
select a, b
from
(
select foo1, foo2, foo3, foo4
from table1
where table1.id = @TableID
) tab_in
unpivot
(a for b in (foo1, foo2, foo3, foo4)) tab_out
union all
select t3.a, t3.b,
from table1 t1
join t2 on t1.id = t2.id
join t3 on t3.id = t2.id
where t1.id = @TableID
union all
select t4.a, t4.b,
from table1 t1
join t4 on t4.id = t4.id
where t1.id = @TableID
)
this is obviously highly repetitive. Two things stand out
table1
is given the same filter thrice. I'd replace it with a CTE, but the select list is different between the first use the rest, so this could have a big performance hit depending on the indexing situation.- The
union all
s all look very similar. The fact that I could have also written theunpivot
as a set of threeunion all
s suggests that the twounion all
s that are currently within the query should somehow be merged in to theunpivot
.
Is there anything in T-SQL that can tackle these two problems?