Hi,
In your query you are trying a lot of stuff
- Creating a Lot of Temp Tables and Indexes.
- Using these Temp Tables to join/filter with your main query
- Drop your Temp tables
SQL Server Depends on statistics and Indexes to generate an execution plan. When these conditions change the execution plan becomes invalid. As and when you drop the temp tables the execution plans become invalid and it needs to be recompiled.
Additionally, You are using a lot of Optional parameters and using 'OR' to join various conditions. This is one of the killing situations. You may have to try with IF conditions to make them choose the correct plan.
In situations like this I have tried these options.
- Instead of Temp tables I have used Permanant tables. I have added an additional key SPID to make sure I do not read someone else's data.
- I seperate different scenarios and write different SQL statements for them. Yes, it is a pain for developer from maintainability point of view, but you will, not only increase the performance but also make the code easier to debug
Hope this helps!