sql-server - 删除或不删除存储过程中的临时表

标签 sql-server stored-procedures temp-tables

我看过这个问题很多次了,但是我找不到能使我满意的答案。基本上,人们和书中所说的是:“尽管临时表超出范围会被删除,但是当不再需要临时表以减少服务器上的资源需求时,您应该显式删除它们”。

对我来说很清楚,当您在Management Studio中工作并创建表时,在关闭窗口或断开连接之前,您将为该表使用一些资源,从逻辑上讲,最好删除它们。

但是,当您使用过程时,如果您最想清理表,那么您很可能会在表的末尾执行该操作(我不是在谈论当您真的不需要表时删除表的情况)。程序)。所以工作流程是这样的:

当您加入SP时:

  • SP执行开始
  • 做一些事情
  • 删除表
  • 执行结束

  • 据我了解,如果您不掉线,它怎么可能工作:
  • SP执行开始
  • 做一些事情
  • 执行结束
  • 删除表

  • 这有什么区别?我只能想象需要一些资源来标识临时表。还有其他想法吗?

    更新:

    我使用2 SP进行了简单测试:
    create procedure test  as
    begin
    create table #temp (a int)
    insert into #temp values (1);
    drop table #temp;
    end
    

    另一个没有drop语句。我启用了用户统计信息并运行了测试:
    declare @i int = 0;
     while @i < 10000
     begin
     exec test;
     SET @i= @i + 1;
     end
    

    那就是我所拥有的(SP中的1-3删除表,4-6不会删除)
    enter image description here

    如图所示,当我不删除临时表时,所有统计信息相同或有所下降。

    UPDATE2:

    我第二次运行了该测试,但是现在有10万次调用,并且还添加了SET NOCOUNT ON。结果如下:
    enter image description here

    正如第二次运行确认的那样,如果您不将表放到SP中,那么您实际上可以节省一些用户时间,因为这是由其他一些内部过程完成的,但不在用户时间范围内。

    最佳答案

    您可以在Paul White的这篇文章中了解更多信息:Temporary Tables in Stored Procedures

    CREATE and DROP, Don’t

    I will talk about this in much more detail in my next post, but the key point is that CREATE TABLE and DROP TABLE do not create and drop temporary tables in a stored procedure, if the temporary object can be cached. The temporary object is renamed to an internal form when DROP TABLE is executed, and renamed back to the same user-visible name when CREATE TABLE is encountered on the next execution. In addition, any statistics that were auto-created on the temporary table are also cached. This means that statistics from a previous execution remain when the procedure is next called.

    关于sql-server - 删除或不删除存储过程中的临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46314985/

    相关文章:

    sql - 用于逆透视的存储过程

    mysql - 存储过程中的 "@"符号?

    SQL Server 2008 R2 - 为什么我的临时表认为它有一个标识列?

    c# - 如何使用 Entity Framework Core 进行全文搜索?

    sql-server - 可以使用不同的访问权限进行跨模态视图查询吗?

    MySQL 8.0 : How to Alter Procedure Definer

    sql - 在Sql Server中,如何将游标中的值放入临时表中?

    sql-server-2014 - 在 SQL Server 2014 中找不到用户定义的数据类型 'empnum'

    sql - 计算第 95 个百分位值?

    sql - 如何备份Sql Server到sql文件?