In the application I am working on, we have data grids that have the capability to display custom views of the data. As a point of reference, we modeled this feature using the concept of views as they exist in SharePoint.
The custom views should have the following capabilities:
- Be able to define which subset of columns (of those that are available) should be displayed in the view.
- Be able to define one or more filters for retrieving data. These filters are not constrained to use only the columns that are in the result set but must use one of the available columns. Standard logical conditions and operators apply to these filters. For example, ColumnA Equals Value1 or ColumnB >= Value2.
- Be able to define a set of columns that the data will be sorted by. This set of columns can be one or more columns from the set of columns that will be returned in the result set.
- Be able to define a set of columns that the data will be grouped by. This set of columns can be one or more columns from the set of columns that will be returned in the result set.
I have application code that will dynamically generate the necessary SQL to retrieve the appropriate set of data. However, it appears to perform poorly. When I run across a poorly performing query, my first thought is to determine where indexes might help. The problem here is that I won't necessarily know which indexes need to be created as the underlying query could retrieve data in many different ways.
Essentially, the SQL that is currently being used does the following:
- Creates a temporary table variable to hold the filtered data. This table contains a column for each column that should be returned in the result set.
- Inserts data that matches the filter into the table variable.
- Queries the table variable to determine the total number of rows of data.
- If requested, determines the grouping values of the data in the table variable using the specified grouping columns.
- Returns the requested page of the requested page size of data from the table variable, sorted by any specified sort columns.
My question is what are some ways that I may improve this process? For example, one idea I had was to have my table variable only contain the columns of data that are used to group and sort and then join in the source table at the end to get the rest of the displayed data. I am not sure if this would make any difference which is the reason for this post.
I need to support versions 2014, 2016 and 2017 of SQL Server in addition to SQL Azure. Essentially, I will not be able to use a specific feature of an edition of SQL Server unless that feature is available in all of the aforementioned platforms.