简体   繁体   中英

Best practice for using SQL Server Temp Tables

I have a dashboard web application that involves users logging in to query large amounts of data (MS SQL Server 2016) and view charts of the results. The data also changes frequently (say every hour). Performance is particularly important.

To improve performance I've found that I can create a temp table once, which handles a bulk amount of the processing, then re-query that table multiple times (eg. grouping by different fields) to produce different charts. When the user first logs in I can use this method to quickly pre-caclulate a lot of the chart data for a user in one go. This is much more efficient than doing the whole query each time (ie. doing "temp table + group by" separately for each of the 20 charts).

However, once the user has logged in, there are other actions he can take where he could re-use that temp table data. Ideally i don't want to recreate the temp table on each subsequent request, so i'd like to re-use it for the lifetime of the client login.

I don't think I could use a global table, as I'd need a separate one for each user. Also SQL Server wouldn't know when to delete the table if the user's session timed out on the client, potentially leading to a build-up of lots of old temp tables & massive amount of data.

Ideally I'd like a session temp table that would expire say every hour, so the client could access the data for multiple subsequent requests and it wouldn't have to be recreated that often.

What are my options for doing this?

The only time I would suggest using temp tables for quick retrieval of any data would be data that is final. Meaning nobody would change it. An obituary would be a good listing for that. If you do this then potentially each person would end up with different data in their charts. Person A queries and gets a temp table of data and creates charts. Person B queries and gets a temp table of all new and modified data and creates charts. Person A queries again and gets the original data from their 1st query and never sees what person B sees. I would not suggest this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM