I have a query that runs in around 6 seconds. At present, it outputs about 1500 records that are then inserted into a table variable. The insert into the table takes an overwhelming 7 seconds.
If I try the same thing with a temporary table, the insert only takes about a second.
The problem is that the query is placed inside a TVF (and there are a lot of dependencies on that function so converting it to a stored procedure isn't the most ideal resolution) so I can't use temporary tables.
Is there any way to speed up the inserts into the table variable? I'm using SQL Server 2012 so memory-optimized table variables aren't an option either.
Would appreciate any advice, thanks in advance!
EDIT (Additional information):
I tried a CTE approach similar to the one shown here and the overhead is similar to using the temporary table approach, the query takes around 8 seconds now. There are three of these table variables (each giving a slightly different output) so combined, the query takes around 24 seconds total, which is quite acceptable for what we use it for.