SQL Server Temp table vs Table Variable
Our client's database admins have requested that we don't use temp tables within our reporting stored procedures (#Table
), but instead, make use of table variables.
Are table variables less efficient than temp tables?
Also, if I create a table as #table
, as opposed to ##table
, the one with o开发者_开发知识库ne #
is a session table, as opposed to the ##
which is global, right? When the stored procedure
is completed, and you don't do a DROP TABLE #table
... does #table
still exist? If it's session based, then will I ever have access to it again?
Table variables can lead to fewer stored procedure recompilations than temporary tables (see KB #243586 and KB #305977), and — since they cannot be rolled back — do not bother with the transaction log.
##table
is belogs to global temporary table. yes #table not exist because its in given scope only and you never access it out the given scope.
Edit
I also like to point make use of CTE(Common Table Expressions) because it also somehow work as temporary table. Check this answer for detail : Which are more performant, CTE or temporary tables?
I'm not 100% sure what you're asking, since your title mentions Table Variables, you're asked to use Table Variables, but your question asks nothing about Table Variables... But table variables are declared like:
DECLARE @Banana TABLE
(
Id INT,
Name VARCHAR(20)
)
If local temporary table (#table) was created in SP, it is dropped after SP is finished. BOL says:
Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped by using DROP TABLE:
A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table.
All other local temporary tables are dropped automatically at the end of the current session.
Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.
精彩评论