复制或克隆带有约束的 SQL 表
Posted
技术标签:
【中文标题】复制或克隆带有约束的 SQL 表【英文标题】:Copy or Clone SQL table with constraints 【发布时间】:2012-11-19 10:15:32 【问题描述】:我想在另一个表中创建相同的表结构..
但它应该使用旧表的所有主键和索引创建相同的表结构。
我在下面尝试过,但它只复制列……不是主键也不是索引。
SELECT *
INTO dbo.NewTable
FROM dbo.ExistingTable
WHERE 1 = 2
我怎样才能复制/克隆它呢?
【问题讨论】:
【参考方案1】:我正在向您发布我用来创建数据库克隆的脚本的一部分,我删除了一些部分并且它缺少 FK 和索引(但是 PK 在那里,忽略身份:P)但应该给你一个提示关于如何做到这一点
注意:它没有经过优化,因为我需要运行 1 次而不是按计划运行,我只是让它与我的数据库一起工作:P 根据您的需要修复它:
declare @DestinationSchema nvarchar(50) = 'frontier'
declare @SourceSchema nvarchar(50) = 'dbo'
select so.name as TableName
,N'create table [' + @DestinationSchema + '].[' + so.name + '] (' + o.list + (case when kc.name IS NULL then '' else ' CONSTRAINT ' + kc.name + ' PRIMARY KEY CLUSTERED ' + ' (' + LEFT(j.List, Len(j.List)-1) + '))' end) as TableScript
from sys.objects so
cross apply
(select
-- column name
' ['+cl.name+'] ' +
-- column type
t.name +
-- type lenght
(case t.name
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'bit' then ''
when 'int' then ''
when 'tinyint' then ''
when 'smallint' then ''
when 'bigint' then ''
when 'timestamp' then ''
when 'date' then ''
when 'smalldatetime' then ''
when 'datetime' then ''
when 'datetime2' then ''
when 'real' then ''
when 'float' then ''
when 'time' then ''
when 'decimal' then '(' + cast(cl.[precision] as varchar) + ', ' + cast(cl.scale as varchar) + ')'
else '('+ (case when cl.max_length = -1 then 'MAX' else cast(cl.max_length as varchar) end) +')' end) + ' ' +
-- nullable
(case when cl.is_nullable = 0 then 'NOT ' else '' end ) + 'NULL,'
from sys.columns cl
inner join sys.types t on cl.user_type_id = t.user_type_id
where object_id = so.object_id
order by cl.column_id
for xml path('')
) o (list)
inner join sys.schemas sch on so.[schema_id] = sch.[schema_id] AND sch.name = @SourceSchema
left join sys.key_constraints kc on so.[object_id] = kc.parent_object_id AND kc.[type] = 'PK' AND kc.[schema_id] = so.[schema_id]
cross apply
(select N'[' + col.name + '], '
from sys.columns col
inner join sys.indexes i on col.[object_id] = i.[object_id] and i.is_primary_key = 1
inner join sys.index_columns ic on ic.object_id = so.object_id and ic.column_id = col.column_id and ic.index_id = i.index_id
where col.[object_id] = so.[object_id]
order by ic.key_ordinal
for xml path('')) j (list)
cross apply
(select N'[Destination].[' + col.name + '] = [Source].[' + col.name + '] AND '
from sys.columns col
inner join sys.indexes i on col.[object_id] = i.[object_id] and i.is_primary_key = 1
inner join sys.index_columns ic on ic.object_id = so.object_id and ic.column_id = col.column_id and ic.index_id = i.index_id
where col.[object_id] = so.[object_id]
order by ic.key_ordinal
for xml path('')) k (list)
where
so.[type] = 'U'
order by
so.name
【讨论】:
以上是关于复制或克隆带有约束的 SQL 表的主要内容,如果未能解决你的问题,请参考以下文章