【问题标题】:Create a temporary table like a current table in SQL Server 2005/2008在 SQL Server 2005/2008 中创建类似于当前表的临时表
【发布时间】:2009-11-06 19:03:52
【问题描述】:

如何在存储过程中创建一个与当前表完全一样的临时表?

【问题讨论】:

    标签: sql sql-server tsql stored-procedures


    【解决方案1】:
    select * into #temp_table from current_table_in_stored_procedure
    
    #temp_table - locally temp
    ##temp_table - globally temp
    
    select top 0 * into #temp_table from current_table_in_stored_procedure to have empty table
    

    【讨论】:

    • 这会将 current_table 中的数据复制到 #temp_table 中,但 #temp_table 不会有相同的键、身份设置等。不过,这是执行此任务的公认方式。
    • @David:临时表继承身份设置,但没有,没有键或索引。我希望我能把它关掉!
    【解决方案2】:

    SELECT * INTO #t FROM table

    如果您希望它为空:

    SELECT * INTO #t FROM table WHERE 1 = 2

    【讨论】:

      【解决方案3】:

      或者,您可以编写现有表的脚本并将名称更改为临时表名称,然后将创建表脚本添加到要运行的其余脚本的顶部。如果临时表与真实表的结构完全匹配真的很重要,我通常会这样做(例如,当我创建一个名为#inserted 的假表以在测试我打算放入触发器中的代码时使用。)

      大多数情况下,虽然 select into 会为您提供所需的内容。

      【讨论】:

        【解决方案4】:

        除了临时表之外,通用表表达式或表变量也可以达到目的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-07
          • 1970-01-01
          • 2010-12-11
          • 2013-02-03
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多