创建一个临时表的TO脚本

5

我在SQL Server 2008 R2中有一个全局临时表。 我需要生成与我们通过SSMS生成脚本的方式相同的脚本,即 "Script table as" -> "Create to"。

实际上,我并没有创建临时表。 我只是尝试使用它的架构创建一个表,以便在事务期间永久存储我的表中的数据。


1
@AaronBertrand,抱歉。你不能做“select * into”,然后使用SSMS生成吗? - sam yi
2
你为什么要使用全局临时表?相比永久表,这有什么优势吗?两者都将并发降至1。 - Aaron Bertrand
3
将##global_temp_table中的前0行数据复制到[anotherdb].[dbo].[formerly_global_table_temp]表中。将此脚本输出?我猜这是我最好的建议。另外,对@AaronBertrand的评论点个赞。 - swasheck
您还可以查询此表以生成脚本。tempdb.information_schema.columns,其中table_name = '##tablename'。 - sam yi
根据您的要求,您应该制作一个表格。 - Zane
显示剩余7条评论
1个回答

5

您无法使用SSMS GUI执行此操作。但是,此代码取自如何在SQL Server中为给定表生成CREATE TABLE语句?

select  'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from    sysobjects so
cross apply
    (SELECT 
        '  ['+column_name+'] ' + 
        data_type + case data_type
            when 'sql_variant' then ''
            when 'text' then ''
            when 'ntext' then ''
            when 'xml' then ''
            when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
            else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
        case when exists ( 
        select id from syscolumns
        where object_name(id)=so.name
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
        ) then
        'IDENTITY(' + 
        cast(ident_seed(so.name) as varchar) + ',' + 
        cast(ident_incr(so.name) as varchar) + ')'
        else ''
        end + ' ' +
         (case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
          case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' 

     from information_schema.columns where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) o (list)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     ORDER BY
        ORDINAL_POSITION
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')

1
那是正确的链接吗?我在那里没有看到类似的东西。 - RBarryYoung
哎呀,我把它改成了正确的。 - PollusB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接