web-dev-qa-db-ja.com

テーブルの完全な構造をコピーする

いくつかの方法を使用して、テーブルのコピーを作成すると、インデックス、PK、FKなどが失われます。たとえば、SQL Serverでは次のように言うことができます。

select * into dbo.table2 from dbo.table1;

これはテーブルの単なるコピーです。すべてのインデックス/制約がありません。 (バックアップを使用せずに)テーブル構造をコピーするにはどうすればよいですか?

私は主にこれを手動で行うことを目指していますが、それが不可能な場合は、解決策を受け入れます。

34
jcho360

もちろん、UIを使用して比較的簡単にテーブルをスクリプト化できます。

enter image description here

これによりCREATE TABLEスクリプトが出力され、古い名前を検索して新しい名前に置き換えるだけで済みます(新しい名前のオブジェクトがまだ存在していないことを確認してください)。

しかし、これを自動化しようとしている場合(たとえば、コードでテーブル作成スクリプトを生成する場合)は、少し面倒です。上記のスクリプトオプションは、CREATE TABLE DDL全体をメタデータの単一の場所からプルするだけではありません。それは、コードの舞台裏で一連の魔法を実行して、最終的なCREATE TABLEスクリプトを生成します(プロファイラーを使用して、データを取得する場所を確認できますが、どのように組み立てられるかは確認できません)。私はこれのためのオプションを提案しました:

http://connect.Microsoft.com/SQLServer/feedback/details/273934

しかし、これは非常に少数の投票で満たされ、マイクロソフトによってすぐに撃墜されました。スキーマを生成するためにサードパーティのツールを使用する方がはるかに価値があるかもしれません( 私はこれについてブログを書いています )。

SQL Server 2012には、2005年、2008年、および2008 R2で実行する必要がある作業よりもはるかに接近できる新しいメタデータ関数があり、メタデータから列情報をつなぎ合わせます(たとえば、 10進数は精度/スケールを追加する必要があります。[n [var [char]]は長さ指定を追加する必要があります。n[var] charはmax_lengthを半分に切断する必要があります。MAXの場合は、 -1をMAXなどに変更します)。 SQL Server 2012では、この部分は少し簡単です。

SELECT name, system_type_name, is_nullable FROM
  sys.dm_exec_describe_first_result_set('select * from sys.objects', NULL, 0)

結果:

name                   system_type_name  is_nullable
--------------------   ----------------  -----------
name                   nvarchar(128)     0
object_id              int               0
principal_id           int               1
schema_id              int               0
parent_object_id       int               0
type                   char(2)           0
type_desc              nvarchar(60)      1
create_date            datetime          0
modify_date            datetime          0
is_ms_shipped          bit               0
is_published           bit               0
is_schema_published    bit               0

これについてもブログを書いています。

間違いなく、これはCREATE TABLEを使用した複雑なアプローチよりもターゲットのsys.columnsステートメントにはるかに近いですが、まだやらなければならないことがたくさんあります。キー、制約、行内テキストオプション、ファイルグループ情報、圧縮設定、インデックスなど。これは非常に長いリストであり、これを繰り返す代わりに、サードパーティのツールを検討することをお勧めします。 -ホイールを再発明したアナロジーを使用。

つまり、コードでこれを行う必要があるがSQL Serverの外部で実行できる場合は、SMO/PowerShellを検討できます。 this tip および Scripter.Script()method を参照してください。

31
Aaron Bertrand

私はこのspを書いて、すべてのもの、pk、fk、パーティション、制約を含むスキーマを自動的に作成しました...

重要!!実行前

create type TestTableType as table (ObjectID int)

ここでSP:

    SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


    --*************************************************************************************************'
--    La procedura crea lo script di una tabella
--    Tabella   : xxxxx
--    Creata da : E.Mantovanelli
--    Data creazione : 28-06-2012
--    Data modifica: 28-06-2012
--*************************************************************************************************'

/*
    --      ID----|-----Data-----|--    User        ---------   | ----  Note
                        20-11-2013      E.Mantovanelli                  distinzione schema delle tabelle
                                                                        estrazione da db selezionato
                                                                        aggiunta estrazione partizione
*/

CREATE PROCEDURE [dbo].[util_ScriptTable] 
     @DBName SYSNAME
    ,@schema sysname
    ,@TableName SYSNAME
    ,@IncludeConstraints BIT = 1
    ,@IncludeIndexes BIT = 1
    ,@NewTableSchema sysname
    ,@NewTableName SYSNAME = NULL
    ,@UseSystemDataTypes BIT = 0
    ,@script varchar(max) output
AS 
BEGIN try
    if not exists (select * from sys.types where name = 'TestTableType')
        create type TestTableType as table (ObjectID int)--drop type TestTableType

    declare @sql nvarchar(max)

    DECLARE @MainDefinition TABLE (FieldValue VARCHAR(200))
    --DECLARE @DBName SYSNAME
    DECLARE @ClusteredPK BIT
    DECLARE @TableSchema NVARCHAR(255)

    --SET @DBName = DB_NAME(DB_ID())
    SELECT @TableName = name FROM sysobjects WHERE id = OBJECT_ID(@TableName)

    DECLARE @ShowFields TABLE (FieldID INT IDENTITY(1,1)
                                        ,DatabaseName VARCHAR(100)
                                        ,TableOwner VARCHAR(100)
                                        ,TableName VARCHAR(100)
                                        ,FieldName VARCHAR(100)
                                        ,ColumnPosition INT
                                        ,ColumnDefaultValue VARCHAR(100)
                                        ,ColumnDefaultName VARCHAR(100)
                                        ,IsNullable BIT
                                        ,DataType VARCHAR(100)
                                        ,MaxLength varchar(10)
                                        ,NumericPrecision INT
                                        ,NumericScale INT
                                        ,DomainName VARCHAR(100)
                                        ,FieldListingName VARCHAR(110)
                                        ,FieldDefinition CHAR(1)
                                        ,IdentityColumn BIT
                                        ,IdentitySeed INT
                                        ,IdentityIncrement INT
                                        ,IsCharColumn BIT 
                                        ,IsComputed varchar(255))

    DECLARE @HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
                                        ,Flds VARCHAR(4000)
                                        ,FldValue CHAR(1) DEFAULT(0))

    DECLARE @PKObjectID TABLE(ObjectID INT)

    DECLARE @Uniques TABLE(ObjectID INT)

    DECLARE @HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
                                                ,Flds VARCHAR(4000)
                                                ,FldValue CHAR(1) DEFAULT(0))

    DECLARE @Definition TABLE(DefinitionID SMALLINT IDENTITY(1,1)
                                        ,FieldValue VARCHAR(200))


  set @sql=
  '
  use '+@DBName+'
  SELECT distinct DB_NAME()
            ,TABLE_SCHEMA
            ,TABLE_NAME
            ,''[''+COLUMN_NAME+'']'' as COLUMN_NAME
            ,CAST(ORDINAL_POSITION AS INT)
            ,COLUMN_DEFAULT
            ,dobj.name AS ColumnDefaultName
            ,CASE WHEN c.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
            ,DATA_TYPE
            ,case CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
            ,CAST(NUMERIC_PRECISION AS INT)
            ,CAST(NUMERIC_SCALE AS INT)
            ,DOMAIN_NAME
            ,COLUMN_NAME + '',''
            ,'''' AS FieldDefinition
            ,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
            ,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
            ,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
            ,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn 
            ,cc.definition 
            FROM INFORMATION_SCHEMA.COLUMNS c
            JOIN sys.columns sc ON  c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
            LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
            JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
            LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = ''D''
            left join sys.computed_columns cc on c.TABLE_NAME=OBJECT_NAME(cc.object_id) and sc.column_id=cc.column_id
    WHERE c.TABLE_NAME = @TableName and c.TABLE_SCHEMA=@schema 
    ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
    '

  print @sql
  INSERT INTO @ShowFields( DatabaseName
                                    ,TableOwner
                                    ,TableName
                                    ,FieldName
                                    ,ColumnPosition
                                    ,ColumnDefaultValue
                                    ,ColumnDefaultName
                                    ,IsNullable
                                    ,DataType
                                    ,MaxLength
                                    ,NumericPrecision
                                    ,NumericScale
                                    ,DomainName
                                    ,FieldListingName
                                    ,FieldDefinition
                                    ,IdentityColumn
                                    ,IdentitySeed
                                    ,IdentityIncrement
                                    ,IsCharColumn
                                    ,IsComputed)

    exec sp_executesql @sql,
                       N'@TableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@schema=@schema            
    /*
    SELECT @DBName--DB_NAME()
            ,TABLE_SCHEMA
            ,TABLE_NAME
            ,COLUMN_NAME
            ,CAST(ORDINAL_POSITION AS INT)
            ,COLUMN_DEFAULT
            ,dobj.name AS ColumnDefaultName
            ,CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END
            ,DATA_TYPE
            ,CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
            ,CAST(NUMERIC_PRECISION AS INT)
            ,CAST(NUMERIC_SCALE AS INT)
            ,DOMAIN_NAME
            ,COLUMN_NAME + ','
            ,'' AS FieldDefinition
            ,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
            ,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
            ,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
            ,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn 
            FROM INFORMATION_SCHEMA.COLUMNS c
            JOIN sys.columns sc ON  c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
            LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
            JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
            LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = 'D'

    WHERE c.TABLE_NAME = @TableName
    ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
    */
    SELECT TOP 1 @TableSchema = TableOwner FROM @ShowFields

    INSERT INTO @HoldingArea (Flds) VALUES('(')

    INSERT INTO @Definition(FieldValue)VALUES('CREATE TABLE ' + CASE WHEN @NewTableName IS NOT NULL THEN @DBName + '.' + @NewTableSchema + '.' + @NewTableName ELSE @DBName + '.' + @TableSchema + '.' + @TableName END)
    INSERT INTO @Definition(FieldValue)VALUES('(')
    INSERT INTO @Definition(FieldValue)
    SELECT   CHAR(10) + FieldName + ' ' + 
        --CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN '' ELSE ',' END 

        CASE WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN DomainName + 
            CASe WHEN IsNullable = 1 THEN ' NULL ' 
            ELSE ' NOT NULL ' 
            END 
        ELSE 
            case when IsComputed is null then
                UPPER(DataType) +
                CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' 
                ELSE 
                    CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')' 
                    ELSE
                        CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')' 
                        ELSE '' 
                        end  
                    end 
                END +
                CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' 
                ELSE '' 
                END +
                CASE WHEN IsNullable = 1 THEN ' NULL ' 
                ELSE ' NOT NULL ' 
                END +
                CASE WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,@TableName,@NewTableName) + '] DEFAULT' + UPPER(ColumnDefaultValue) 
                ELSE '' 
                END 
            else
                ' as '+IsComputed+' '
            end
        END + 
        CASE WHEN FieldID = (SELECT MAX(FieldID) FROM @ShowFields) THEN '' 
        ELSE ',' 
        END 

    FROM    @ShowFields

    IF @IncludeConstraints = 1
        BEGIN    

        set @sql=
        '
        use '+@DBName+'
        SELECT  distinct  '',CONSTRAINT ['' + replace(name,@TableName,@NewTableName) + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')'' 
           FROM ( SELECT   ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
                ,   REVERSE(SUBSTRING(REVERSE((   SELECT cp.name + '',''   
                FROM   sys.foreign_key_columns fkc   
                JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id   
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ParentColumns,   
                REVERSE(SUBSTRING(REVERSE((   SELECT cr.name + '',''   
                FROM   sys.foreign_key_columns fkc  
                JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ReferencedColumns   
                FROM sys.foreign_keys fk    
                    inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=@schema) a    
            WHERE ParentObject = @TableName    
        '

        print @sql

        INSERT INTO @Definition(FieldValue)
        exec sp_executesql @sql,
                   N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
            /*
           SELECT    ',CONSTRAINT [' + name + '] FOREIGN KEY (' + ParentColumns + ') REFERENCES [' + ReferencedObject + '](' + ReferencedColumns + ')'  
           FROM ( SELECT   ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
                ,   REVERSE(SUBSTRING(REVERSE((   SELECT cp.name + ','   
                FROM   sys.foreign_key_columns fkc   
                JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id   
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('')   )), 2, 8000)) ParentColumns,   
                REVERSE(SUBSTRING(REVERSE((   SELECT cr.name + ','   
                FROM   sys.foreign_key_columns fkc  
                JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('')   )), 2, 8000)) ReferencedColumns   
                FROM sys.foreign_keys fk    ) a    
            WHERE ParentObject = @TableName    
            */

            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '',CONSTRAINT ['' + replace(c.name,@TableName,@NewTableName) + ''] CHECK '' + definition 
            FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=@schema    
            WHERE OBJECT_NAME(parent_object_id) = @TableName
            '

            print @sql
            INSERT INTO @Definition(FieldValue) 
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)',
                       @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema
            /*
            SELECT ',CONSTRAINT [' + name + '] CHECK ' + definition FROM sys.check_constraints    
            WHERE OBJECT_NAME(parent_object_id) = @TableName
            */

            set @sql=
            '
            use '+@DBName+'
            SELECT DISTINCT  PKObject = cco.object_id 
            FROM    sys.key_constraints cco    
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id    
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName    AND  i.type = 1 AND    is_primary_key = 1
            '
            print @sql
            INSERT INTO @PKObjectID(ObjectID) 
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@schema varchar(50)',
                               @TableName=@TableName,@schema=@schema
            /*
            SELECT DISTINCT  PKObject = cco.object_id 
            FROM    sys.key_constraints cco    
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id    
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            WHERE    OBJECT_NAME(parent_object_id) = @TableName    AND  i.type = 1 AND    is_primary_key = 1
            */

            set @sql=
            '
            use '+@DBName+'
            SELECT DISTINCT    PKObject = cco.object_id
            FROM    sys.key_constraints cco   
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id  
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName AND  i.type = 2 AND    is_primary_key = 0 AND    is_unique_constraint = 1
            '
            print @sql
            INSERT INTO @Uniques(ObjectID)
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@schema varchar(50)',
                               @TableName=@TableName,@schema=@schema
            /*
            SELECT DISTINCT    PKObject = cco.object_id
            FROM    sys.key_constraints cco   
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id  
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            WHERE    OBJECT_NAME(parent_object_id) = @TableName AND  i.type = 2 AND    is_primary_key = 0 AND    is_unique_constraint = 1
            */

            SET @ClusteredPK = CASE WHEN @@ROWCOUNT > 0 THEN 1 ELSE 0 END

            declare @t TestTableType
            insert @t select * from @PKObjectID
            declare @u TestTableType
            insert @u select * from @Uniques

            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '',CONSTRAINT '' + replace(cco.name,@TableName,@NewTableName) + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END  WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END 
            + ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT   c.name +  + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''    
            FROM   sys.key_constraints ccok   
            LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
            LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id 
            LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id  
            WHERE i.object_id = ccok.parent_object_id AND   ccok.object_id = cco.object_id    
            order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
            FROM sys.key_constraints cco 
            inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            LEFT JOIN @U u ON cco.object_id = u.objectID
            LEFT JOIN @t pk ON cco.object_id = pk.ObjectID    
            WHERE    OBJECT_NAME(cco.parent_object_id) = @TableName 

            '

            print @sql
            INSERT INTO @Definition(FieldValue)
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50),@t TestTableType readonly,@u TestTableType readonly',
                               @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@t=@t,@u=@u

            /*
            SELECT ',CONSTRAINT ' + name + CASE type WHEN 'PK' THEN ' PRIMARY KEY ' + CASE WHEN pk.ObjectID IS NULL THEN ' NONCLUSTERED ' ELSE ' CLUSTERED ' END  WHEN 'UQ' THEN ' UNIQUE ' END + CASE WHEN u.ObjectID IS NOT NULL THEN ' NONCLUSTERED ' ELSE '' END 
            + '(' +REVERSE(SUBSTRING(REVERSE(( SELECT   c.name +  + CASE WHEN cc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','    
            FROM   sys.key_constraints ccok   
            LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
           LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id 
           LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id  
           WHERE i.object_id = ccok.parent_object_id AND   ccok.object_id = cco.object_id    FOR XML PATH(''))), 2, 8000)) + ')'
           FROM sys.key_constraints cco 
           LEFT JOIN @PKObjectID pk ON cco.object_id = pk.ObjectID    
           LEFT JOIN @Uniques u ON cco.object_id = u.objectID
           WHERE    OBJECT_NAME(cco.parent_object_id) = @TableName 
           */
        END

        INSERT INTO @Definition(FieldValue) VALUES(')')

        set @sql=
        '
        use '+@DBName+'
        select '' on '' + d.name + ''([''+c.name+''])''
        from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
                          join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
                          join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
                          join sys.schemas s on t.schema_id=s.schema_id
                          join sys.data_spaces d on i.data_space_id=d.data_space_id
        where t.name=@TableName and s.name=@schema
        order by key_ordinal
        '

        print 'x'
        print @sql
        INSERT INTO @Definition(FieldValue) 
        exec sp_executesql @sql,
                           N'@TableName varchar(50),@schema varchar(50)',
                           @TableName=@TableName,@schema=@schema

        IF @IncludeIndexes = 1
        BEGIN
            set @sql=
            '
            use '+@DBName+'
            SELECT distinct '' CREATE '' + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,@TableName,@NewTableName) + ''] ON '+@DBName+'.'+@NewTableSchema+'.'+@NewTableName+' ('' 
            +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=0
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000)) + '')''+
            ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE((   SELECT name + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=1
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000))+'')'' ,'''')+''''    
            FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
                               join sys.schemas s on t.schema_id=s.schema_id   
            AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 
                where t.name=@TableName and s.name=@schema
            '

            print @sql
            INSERT INTO @Definition(FieldValue)    
            exec sp_executesql @sql,
                               N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50), @ClusteredPK bit',
                               @TableName=@TableName,@NewTableName=@NewTableName,@schema=@schema,@ClusteredPK=@ClusteredPK

        END 

            /*

                SELECT   'CREATE ' + type_desc + ' INDEX [' + [name] COLLATE SQL_Latin1_General_CP1_CI_AS + '] ON [' +  OBJECT_NAME(object_id) + '] (' +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','   
                FROM  sys.index_columns sc  
                JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
                WHERE  OBJECT_NAME(sc.object_id) = @TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                ORDER BY index_column_id ASC   FOR XML PATH('')    )), 2, 8000)) + ')'    
                FROM sys.indexes i    
                WHERE   OBJECT_NAME(object_id) = @TableName
                AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 

            */

            INSERT INTO @MainDefinition(FieldValue)   
            SELECT FieldValue FROM @Definition    
            ORDER BY DefinitionID ASC 

            ----------------------------------

            declare @q  varchar(max)

            set @q=(select replace((SELECT FieldValue FROM @MainDefinition FOR XML PATH('')),'</FieldValue>',''))

            set @script=(select REPLACE(@q,'<FieldValue>',''))
            --drop type TestTableType
END try
-- ##############################################################################################################################################################################
BEGIN CATCH        
    BEGIN
        -- INIZIO  Procedura in errore =========================================================================================================================================================
            PRINT '***********************************************************************************************************************************************************' 
            PRINT 'ErrorNumber               : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
            PRINT 'ErrorSeverity             : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX)) 
            PRINT 'ErrorState                : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX)) 
            PRINT 'ErrorLine                 : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX)) 
            PRINT 'ErrorMessage              : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
            PRINT '***********************************************************************************************************************************************************' 
        -- FINE  Procedura in errore =========================================================================================================================================================
    END 
        set @script=''
    return -1
END CATCH   
-- ##############################################################################################################################################################################   

それを実行するには:

declare @s varchar(max)
exec [util_ScriptTable]   'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,@s output
select @s
9
user31215

これは、手持ち削岩機を使って壁に釘を入れることかもしれませんが、質問の広さを考えると、それは言及するのに有効なオプションだと思います。

SQL Server 2012 SP4 +、2014 SP2 +、または2016 SP1 +を使用している場合、 DBCC CLONEDATABASE を活用して、データベースのデータのスキーマのみのコピーを作成できます。これは、複数のテーブルの包括的なスキーマコピーを生成するのに理想的であり、一連のテーブルをループするプロセスを「自動化」する必要性を軽減できますが、すべてのテーブルコピーが新しい読み取り専用データベース内に作成されることに注意してください。 。

これらのテーブルには、外部キー、主キー、インデックス、および制約が含まれます。また、統計情報とクエリストアデータも含まれます(NO_STATISTICSおよびNO_QUERYSTOREを指定した場合を除く)。

構文は

DBCC CLONEDATABASE (source_database_name, target_database_name)[WITH [NO_STATISTICS][,NO_QUERYSTORE]] 

ブレントオザーには 素晴らしい投稿 が付いていますが、他にも注意すべき点がいくつかありますが、結局のところ、テーブルのコピーを作成する方法と理由は、実際にどのようにして作成するかです。機微は取引ブレーカーです。

5
LowlyDBA

SQL Server Management Studioの「スクリプトの生成」コマンドを使用して、インデックス、トリガー、外部キーなど、テーブルを作成できるスクリプトを取得できます。

SSMS内

  • テーブルがあるデータベースを右クリックします
  • タスク->スクリプトの生成を選択します
  • 「特定のデータベースオブジェクトを選択」を選択します
  • [テーブル]リストを展開し、スクリプトを作成するテーブルの横にあるチェックボックスをオンにします
  • 「次へ」をクリックして、ウィザードの次のページに移動します
  • 保存オプションを必要に応じて設定し、[詳細]ボタンをクリックします
  • 必要に応じて詳細オプションを設定します。特に、「テーブル/ビューのオプション」では、(デフォルトで)インデックス、トリガー、およびフルテキストインデックスがnotスクリプトであることに注意してください。それらが必要な場合は、「False」から「True」に切り替えます。
  • 完了したら、[OK]をクリックして詳細オプションを保存し、[次へ]をクリックして選択内容を確認します。もう一度「次へ」をクリックして、実際にスクリプトを生成します。

次に、編集して、必要なものだけを宛先データベースに含めることができます。

4
Martin

これは、このスレッドのE.Mantovanelliによるバージョンに基づいたバージョンです。これにより、結果のスクリプトに一意のインデックスがキーワードUNIQUEを含まなかった問題が修正されます。また、パラメーターを追加して、非クラスター化インデックスなしでテーブルを作成したり、非クラスター化インデックスのみをスクリプト化したりできるようにします。これを使用してステージテーブルを作成し、それをロードして非クラスター化インデックスを追加し、テーブルの切り替えを行います。これにより、ロードの実行が速くなり、インデックスがフラグメント化されません。

SET ANSI_NULLS ON;
GO

SET QUOTED_IDENTIFIER ON;
GO

--*************************************************************************************************'
--    La procedura crea lo script di una tabella
--    Tabella   : xxxxx
--    Creata da : E.Mantovanelli
--    Data creazione : 28-06-2012
--    Data modifica: 28-06-2012
--*************************************************************************************************'

/*
    --      ID----|-----Data-----|--    User        ---------   | ----  Note
                        20-11-2013      E.Mantovanelli                  distinzione schema delle tabelle
                                                                        estrazione da db selezionato
                                                                        aggiunta estrazione partizione
*/
--*************************************************************************************************'
--    Creates a copy of a table with optionally all indexes and constraints depending on parameters
--    Updated by : Brent Willis
--    Date Updated : 09-11-2019
--    Changes: Added the ability to create a table with clustered index and constraints only or to 
--             CREATE just the non-clustered indexes. This is helpful so a table can be created, 
--             loaded then non-clusted indexes added so it can them be swapped into a partitioned 
--             table with freshly created indexes to lower fragmentation. 
--
--             Also fixed an issue when a unique index was defined the index resulting table was not unique. 
--*************************************************************************************************'

ALTER PROCEDURE dbo.util_ScriptTable
    @DBName                sysname
  , @schema                sysname
  , @TableName             sysname
  , @includeTable          Bit     = 1
  , @IncludeConstraints    Bit     = 1
  , @IncludeClusteredIndex Bit     = 1
  , @IncludeIndexes        Bit     = 1
  , @NewTableSchema        sysname
  , @NewTableName          sysname = NULL
  , @UseSystemDataTypes    Bit     = 0
  , @script                Varchar(MAX) OUTPUT
AS
    BEGIN TRY
        IF NOT EXISTS (SELECT * FROM sys.types WHERE name = 'TestTableType')
            CREATE TYPE TestTableType AS TABLE (ObjectID Int); --drop type TestTableType

        DECLARE @sql NVarchar(MAX);

        DECLARE @MainDefinition Table (FieldValue Varchar(200));

        --DECLARE @DBName SYSNAME
        DECLARE @ClusteredPK Bit;
        DECLARE @TableSchema NVarchar(255);

        --SET @DBName = DB_NAME(DB_ID())
        SELECT @TableName = name FROM sys.sysobjects WHERE id = Object_Id(@TableName);

        DECLARE @ShowFields Table (FieldID            Int IDENTITY(1, 1)
                                 , DatabaseName       Varchar(100)
                                 , TableOwner         Varchar(100)
                                 , TableName          Varchar(100)
                                 , FieldName          Varchar(100)
                                 , ColumnPosition     Int
                                 , ColumnDefaultValue Varchar(100)
                                 , ColumnDefaultName  Varchar(100)
                                 , IsNullable         Bit
                                 , DataType           Varchar(100)
                                 , MaxLength          Varchar(10)
                                 , NumericPrecision   Int
                                 , NumericScale       Int
                                 , DomainName         Varchar(100)
                                 , FieldListingName   Varchar(110)
                                 , FieldDefinition    Char(1)
                                 , IdentityColumn     Bit
                                 , IdentitySeed       Int
                                 , IdentityIncrement  Int
                                 , IsCharColumn       Bit
                                 , IsComputed         Varchar(255));

        DECLARE @HoldingArea Table (FldID SmallInt IDENTITY(1, 1), Flds Varchar(4000), FldValue Char(1) DEFAULT (0));

        DECLARE @PKObjectID Table (ObjectID Int);

        DECLARE @Uniques Table (ObjectID Int);

        DECLARE @Definition Table (DefinitionID SmallInt IDENTITY(1, 1), FieldValue Varchar(2000));

        SET @sql = N'
  use ' + @DBName + N'
  SELECT distinct DB_NAME()
            ,TABLE_SCHEMA
            ,TABLE_NAME
            ,''[''+COLUMN_NAME+'']'' as COLUMN_NAME
            ,CAST(ORDINAL_POSITION AS INT)
            ,COLUMN_DEFAULT
            ,dobj.name AS ColumnDefaultName
            ,CASE WHEN c.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
            ,DATA_TYPE
            ,case CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
            ,CAST(NUMERIC_PRECISION AS INT)
            ,CAST(NUMERIC_SCALE AS INT)
            ,DOMAIN_NAME
            ,COLUMN_NAME + '',''
            ,'''' AS FieldDefinition
            ,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
            ,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
            ,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
            ,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn 
            ,cc.definition 
            FROM INFORMATION_SCHEMA.COLUMNS c
            JOIN sys.columns sc ON  c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
            LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
            JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
            LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = ''D''
            left join sys.computed_columns cc on c.TABLE_NAME=OBJECT_NAME(cc.object_id) and sc.column_id=cc.column_id
    WHERE c.TABLE_NAME = @TableName and c.TABLE_SCHEMA=@schema 
    ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
    '   ;

        --PRINT @sql;
        INSERT INTO @ShowFields (DatabaseName
                               , TableOwner
                               , TableName
                               , FieldName
                               , ColumnPosition
                               , ColumnDefaultValue
                               , ColumnDefaultName
                               , IsNullable
                               , DataType
                               , MaxLength
                               , NumericPrecision
                               , NumericScale
                               , DomainName
                               , FieldListingName
                               , FieldDefinition
                               , IdentityColumn
                               , IdentitySeed
                               , IdentityIncrement
                               , IsCharColumn
                               , IsComputed)
        EXEC sys.sp_executesql @sql
                             , N'@TableName varchar(50),@schema varchar(50)'
                             , @TableName = @TableName
                             , @schema = @schema;

        SELECT TOP 1 @TableSchema = TableOwner FROM @ShowFields;

        INSERT INTO @HoldingArea (Flds) VALUES ('(');

        IF @includeTable = 1
            BEGIN
                INSERT INTO @Definition (FieldValue)
                VALUES
                (   'CREATE TABLE ' + CASE
                                          WHEN @NewTableName IS NOT NULL THEN
                                              @DBName + '.' + @NewTableSchema + '.' + @NewTableName
                                          ELSE
                                              @DBName + '.' + @TableSchema + '.' + @TableName
                                      END);

                INSERT INTO @Definition (FieldValue) VALUES ('(');

                INSERT INTO @Definition (FieldValue)
                SELECT Char(10) + FieldName + ' '
                       + CASE
                             WHEN DomainName IS NOT NULL AND @UseSystemDataTypes = 0 THEN
                                 DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END
                             ELSE
                                 CASE
                                     WHEN IsComputed IS NULL THEN
                                         Upper(DataType)
                                         + CASE
                                               WHEN IsCharColumn = 1 THEN
                                                   '(' + Cast(MaxLength AS Varchar(10)) + ')'
                                               ELSE
                                                   CASE
                                                       WHEN DataType = 'numeric' THEN
                                                           '(' + Cast(NumericPrecision AS Varchar(10)) + ','
                                                           + Cast(NumericScale AS Varchar(10)) + ')'
                                                       ELSE
                                                           CASE
                                                               WHEN DataType = 'decimal' THEN
                                                                   '(' + Cast(NumericPrecision AS Varchar(10)) + ','
                                                                   + Cast(NumericScale AS Varchar(10)) + ')'
                                                               ELSE
                                                                   ''
                                                           END
                                                   END
                                           END
                                         + CASE
                                               WHEN IdentityColumn = 1 THEN
                                                   ' IDENTITY(' + Cast(IdentitySeed AS Varchar(5)) + ','
                                                   + Cast(IdentityIncrement AS Varchar(5)) + ')'
                                               ELSE
                                                   ''
                                           END + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END
                                         + CASE
                                               WHEN ColumnDefaultName IS NOT NULL AND @IncludeConstraints = 1 THEN
                                                   'CONSTRAINT ['
                                                   + Replace(ColumnDefaultName, @TableName, @NewTableName)
                                                   + '] DEFAULT' + Upper(ColumnDefaultValue)
                                               ELSE
                                                   ''
                                           END
                                     ELSE
                                         ' as ' + IsComputed + ' '
                                 END
                         END + CASE
                                   WHEN FieldID = (SELECT Max(FieldID)FROM @ShowFields) THEN
                                       ''
                                   ELSE
                                       ','
                               END
                FROM @ShowFields;

                --------------------------------------------------
                IF @IncludeConstraints = 1
                    BEGIN
                        SET @sql = N'
        use ' +         @DBName + N'
        SELECT  distinct  '',CONSTRAINT ['' + replace(name,@TableName,@NewTableName) + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')'' 
           FROM ( SELECT   ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
                ,   REVERSE(SUBSTRING(REVERSE((   SELECT cp.name + '',''   
                FROM   sys.foreign_key_columns fkc   
                JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id   
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ParentColumns,   
                REVERSE(SUBSTRING(REVERSE((   SELECT cr.name + '',''   
                FROM   sys.foreign_key_columns fkc  
                JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
                WHERE fkc.constraint_object_id = fk.object_id   FOR XML PATH('''')   )), 2, 8000)) ReferencedColumns   
                FROM sys.foreign_keys fk    
                    inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=@schema) a    
            WHERE ParentObject = @TableName    
        '               ;

                        --PRINT @sql;
                        INSERT INTO @Definition (FieldValue)
                        EXEC sys.sp_executesql @sql
                                             , N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)'
                                             , @TableName = @TableName
                                             , @NewTableName = @NewTableName
                                             , @schema = @schema;

                        SET @sql = N'
            use ' +     @DBName + N'
            SELECT distinct '',CONSTRAINT ['' + replace(c.name,@TableName,@NewTableName) + ''] CHECK '' + definition 
            FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=@schema    
            WHERE OBJECT_NAME(parent_object_id) = @TableName
            '           ;

                        --PRINT @sql;
                        INSERT INTO @Definition (FieldValue)
                        EXEC sys.sp_executesql @sql
                                             , N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50)'
                                             , @TableName = @TableName
                                             , @NewTableName = @NewTableName
                                             , @schema = @schema;

                        SET @sql = N'
            use ' +     @DBName + N'
            SELECT DISTINCT  PKObject = cco.object_id 
            FROM    sys.key_constraints cco    
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id    
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName    AND  i.type = 1 AND    is_primary_key = 1
            '           ;

                        --PRINT @sql;
                        INSERT INTO @PKObjectID (ObjectID)
                        EXEC sys.sp_executesql @sql
                                             , N'@TableName varchar(50),@schema varchar(50)'
                                             , @TableName = @TableName
                                             , @schema = @schema;

                        SET @sql = N'
            use ' +     @DBName + N'
            SELECT DISTINCT    PKObject = cco.object_id
            FROM    sys.key_constraints cco   
            JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id  
            JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
            join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            WHERE    OBJECT_NAME(parent_object_id) = @TableName AND  i.type = 2 AND    is_primary_key = 0 AND    is_unique_constraint = 1
            '           ;

                        --PRINT @sql;
                        INSERT INTO @Uniques (ObjectID)
                        EXEC sys.sp_executesql @sql
                                             , N'@TableName varchar(50),@schema varchar(50)'
                                             , @TableName = @TableName
                                             , @schema = @schema;

                        SET @ClusteredPK = CASE WHEN @@ROWCOUNT > 0 THEN 1 ELSE 0 END;

                        DECLARE @t TestTableType;

                        INSERT @t SELECT * FROM @PKObjectID;

                        DECLARE @u TestTableType;

                        INSERT @u SELECT * FROM @Uniques;

                        SET @sql = N'
            use ' +     @DBName + N'
            SELECT distinct '',CONSTRAINT '' + replace(cco.name,@TableName,@NewTableName) + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END  WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END 
            + ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT   c.name +  + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''    
            FROM   sys.key_constraints ccok   
            LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
            LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id 
            LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id  
            WHERE i.object_id = ccok.parent_object_id AND   ccok.object_id = cco.object_id    
            order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
            FROM sys.key_constraints cco 
            inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=@schema
            LEFT JOIN @U u ON cco.object_id = u.objectID
            LEFT JOIN @t pk ON cco.object_id = pk.ObjectID    
            WHERE    OBJECT_NAME(cco.parent_object_id) = @TableName 

            '           ;

                        --PRINT @sql;
                        INSERT INTO @Definition (FieldValue)
                        EXEC sys.sp_executesql @sql
                                             , N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50),@t TestTableType readonly,@u TestTableType readonly'
                                             , @TableName = @TableName
                                             , @NewTableName = @NewTableName
                                             , @schema = @schema
                                             , @t = @t
                                             , @u = @u;
                    END;

                INSERT INTO @Definition (FieldValue) VALUES (')');
            END;

        SET @sql = N'
        use ' + @DBName
                   + N'
        select '' on '' + d.name + ''([''+c.name+''])''
        from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
                          join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
                          join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
                          join sys.schemas s on t.schema_id=s.schema_id
                          join sys.data_spaces d on i.data_space_id=d.data_space_id
        where t.name=@TableName and s.name=@schema
        order by key_ordinal
        ';

        PRINT 'x';

        --PRINT @sql;
        INSERT INTO @Definition (FieldValue)
        EXEC sys.sp_executesql @sql
                             , N'@TableName varchar(50),@schema varchar(50)'
                             , @TableName = @TableName
                             , @schema = @schema;

        IF @IncludeClusteredIndex = 1
            BEGIN
                SET @sql = N'
            use ' + @DBName
                           + N'
            SELECT distinct '' CREATE '' + CASE WHEN i.is_unique = 1 THEN ''UNIQUE '' ELSE '''' end + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,@TableName,@NewTableName) + ''] ON '
                           + @DBName + N'.' + @NewTableSchema + N'.' + @NewTableName
                           + N' ('' 
            +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=0
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000)) + '')''+
            ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE((   SELECT name + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=1 
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000))+'')'' ,'''')+''''    
            FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
                               join sys.schemas s on t.schema_id=s.schema_id   
            AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 
                where t.name=@TableName and s.name=@schema and i.type_desc = ''CLUSTERED''
            '   ;

                --PRINT @sql;
                INSERT INTO @Definition (FieldValue)
                EXEC sys.sp_executesql @sql
                                     , N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50), @ClusteredPK bit'
                                     , @TableName = @TableName
                                     , @NewTableName = @NewTableName
                                     , @schema = @schema
                                     , @ClusteredPK = @ClusteredPK;
            END;

        IF @IncludeIndexes = 1
            BEGIN
                SET @sql = N'
            use ' + @DBName
                           + N'
            SELECT distinct '' CREATE '' + CASE WHEN i.is_unique = 1 THEN ''UNIQUE '' ELSE '''' end + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,@TableName,@NewTableName) + ''] ON '
                           + @DBName + N'.' + @NewTableSchema + N'.' + @NewTableName
                           + N' ('' 
            +   REVERSE(SUBSTRING(REVERSE((   SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=0
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000)) + '')''+
            ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE((   SELECT name + '',''   
            FROM  sys.index_columns sc  
            JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id   
            WHERE  t.name=@TableName AND  sc.object_id = i.object_id AND  sc.index_id = i.index_id   
                                         and is_included_column=1 
            ORDER BY key_ordinal ASC   FOR XML PATH('''')    )), 2, 8000))+'')'' ,'''')+''''    
            FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
                               join sys.schemas s on t.schema_id=s.schema_id   
            AND CASE WHEN @ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1   AND is_unique_constraint = 0   AND is_primary_key = 0 
                where t.name=@TableName and s.name=@schema and i.type_desc <> ''CLUSTERED''
            '   ;

                PRINT @sql;

                INSERT INTO @Definition (FieldValue)
                EXEC sys.sp_executesql @sql
                                     , N'@TableName varchar(50),@NewTableName varchar(50),@schema varchar(50), @ClusteredPK bit'
                                     , @TableName = @TableName
                                     , @NewTableName = @NewTableName
                                     , @schema = @schema
                                     , @ClusteredPK = @ClusteredPK;
            END;

        --SELECT * FROM @Definition;
        INSERT INTO @MainDefinition (FieldValue)
        SELECT FieldValue FROM @Definition ORDER BY DefinitionID ASC;

        --SELECT * FROM @MainDefinition;

        ----------------------------------
        DECLARE @q Varchar(MAX);

        SET @q = (SELECT Replace((SELECT FieldValue FROM @MainDefinition FOR XML PATH('')), '</FieldValue>', ''));
        SET @script = (SELECT Replace(@q, '<FieldValue>', ''));
    END TRY
    -- ##############################################################################################################################################################################
    BEGIN CATCH
        BEGIN
            -- INIZIO  Procedura in errore =========================================================================================================================================================
            PRINT '***********************************************************************************************************************************************************';
            PRINT 'ErrorNumber               : ' + Cast(Error_Number() AS NVarchar(MAX));
            PRINT 'ErrorSeverity             : ' + Cast(Error_Severity() AS NVarchar(MAX));
            PRINT 'ErrorState                : ' + Cast(Error_State() AS NVarchar(MAX));
            PRINT 'ErrorLine                 : ' + Cast(Error_Line() AS NVarchar(MAX));
            PRINT 'ErrorMessage              : ' + Cast(Error_Message() AS NVarchar(MAX));
            PRINT '***********************************************************************************************************************************************************';
        -- FINE  Procedura in errore =========================================================================================================================================================
        END;

        SET @script = '';

        RETURN -1;
    END CATCH;
-- ##############################################################################################################################################################################   
0
Brent Willis