Refactoring: Convert expression to cross apply
Working with a query that contains the same expression multiple times, I often want to extract all instances of that expression into a CROSS APPLY for readability and ease of modification, e.g. converting something like this horribleness:
select foo = case when bar < 100 then 'a' when bar > 200 then 'b' else 'c' end, count(*)
from baz
where case when bar < 100 then 'a' when bar > 200 then 'b' else 'c' end in ('a','b')
group by case when bar < 100 then 'a' when bar > 200 then 'b' else 'c' end
into something more manageable like this:
select x.foo, count(*)
from baz
cross apply (
values(case when bar < 100 then 'a' when bar > 200 then 'b' else 'c' end)
) x(foo)
where x.foo in ('a','b')
group by x.foo
I would love to be able to highlight such an expression, right-click, and have a SQL Prompt option for "Convert expression to CROSS APPLY (replace all instances)", similar to Visual Studio's "Introduce Local" refactoring.
