Temporary Table Usage in SQL Server

后端 未结 6 955
礼貌的吻别
礼貌的吻别 2021-02-10 05:20

This is a bit of an open question but I would really like to hear people opinions.

I rarely make use of explicitly declared temporary tables (either table variables or r

6条回答
  •  伪装坚强ぢ
    2021-02-10 05:55

    Temp tables certainly have appropriate uses, they're not a code smell if they're used correctly. One of the nice things about them is that they live in tempdb, which is typically set to Simple recovery model. This means that if you're using temp tables for what they're good for (mostly bulk operations), you're generating a minimal amount of log compared to what the same operation would do on tables in your production db, which probably is in Full recovery model.

    If, as another poster suggested, your production db is on good hardware, but your tempdb isn't, ask your DBA to move it. SQL Server itself uses tempdb quite a bit to process your queries, so it's important for tempdb to have a high performance home.

    Table variables are a different creature entirely. They live only in memory. One good use for them is if you've got a function that you need to call for each row in your query with CROSS APPLY. If that function is expensive, but the number of different results you can get from it is small, you might get significantly higher performance from precomputing the results of all the possible calls (or perhaps all possible calls for your dataset) and storing that in a table variable, then joining to that table variable instead of using CROSS APPLY.

提交回复
热议问题