简体   繁体   English

在SQL Server 2005/2008中创建一个临时表,如当前表

[英]Create a temporary table like a current table in SQL Server 2005/2008

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

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

SELECT * INTO #t FROM table

如果你想要它是空的:

SELECT * INTO #t FROM table WHERE 1 = 2

Alternatively you can script the existing table and change the name to the temp table name and add the create table script to the top of the rest of the script you want to run. 或者,您可以编写现有表的脚本并将名称更改为临时表名称,并将create table脚本添加到要运行的其余脚本的顶部。 I generally do this if it really important the temp table exactly match the structure of the real table (for instance when I am creating a fake table called #inserted to use when testing the code I intend to put into a trigger.) 我通常会这样做,如果真正重要的是临时表与真实表的结构完全匹配(例如当我创建一个名为#inserted的假表时,在测试我打算放入触发器的代码时使用它。)

Most of the time though the select into will get you what you need. 大部分时间虽然选择将获得您所需要的。

公共表表达式或表变量也可以用于除临时表之外的目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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