【问题标题】:Create permanent table based on temporary table in SQL Server在 SQL Server 中基于临时表创建永久表
【发布时间】:2015-12-23 18:56:17
【问题描述】:

我有一个临时表,它聚合来自多个表的列。

我想将此临时表转换为永久表,而无需明确指定列名及其类型。

不知道我解释的够不够

【问题讨论】:

标签: sql-server sql-server-2008 tsql


【解决方案1】:

你可以使用SELECT ... INTO:

SELECT *
INTO dbo.normal_table
FROM #temp_table
-- WHERE 1 = 2;   --add if you only want table structure and not actual data

建表后检查事项:

  • IDENTITY 列和当前值(可能需要重新播种)
  • DEFAULT列的值(如果临时表有默认值,普通表需要ALTERed)
  • COLLATION tempdb 的排序规则可能与您的数据库不同
  • 如果SELECT 包含表达式,则列的大小、精度和比例(VARCHAR、NVARCHAR、CHAR、DECIMAL..)

如果临时表不包含 IDENTITY 列,您可以使用以下方法添加:

SELECT ID  = IDENTITY(INT,1,1)
     ,col1 = NULL   -- NULL by default are treated as INT so you may need casting
     ,col2 = CAST(NULL AS DECIMAL(38,10))
     ,t.*
INTO dbo.table_name
FROM #temp t

【讨论】:

  • 这给出了错误:数据库中已经有一个名为“table_name”的对象。
猜你喜欢
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多