I have a view, vw_example, that is quite complicated and has multiple joins across multiple databases. This view has been causing significant delays when used as part of other queries, and we've narrowed down the problem to execution plan generation.
One thing we've noticed that has vexed us is that this query takes a few seconds to run (and display all the data, ~44k rows):
SELECT * FROM vw_example
whereas this query takes minutes to run (tbl_example is created by the query):
SELECT * INTO tbl_example FROM vw_example
We've additionally compared the SQL execution plans between the two in Microsoft SQL Server Management Studio (2014). The former plan took 3 seconds to generate. The latter plan took 37 minutes.
Comparing the two plans, the only difference is that the latter plan has a "Table Insert" node at the start. Everything else is identical.
Does anyone have any idea why it would take significantly longer to generate a plan for the SELECT INTO statement vs a SELECT statement?
OPTION(FORCE ORDER);
when you select from your view, but whether the execution plan is good or not is unpredictable at times.SELECT * FROM vw_example OPTION(RECOMPILE)
and that makes no difference to the compile time - although I'm not 100% clear that will affect a select statement rather than a stored procedure.OPTION(FORCE ORDER)
got theSELECT INTO
down to 15s! I'll look into what that changes behind the scenes. Thanks.