关于sql server:将数据库模式导出到SQL文件中

Export database schema into SQL file

MS SQL Server 2008中,是否可以将数据库结构导出到T-SQL文件中?

我不仅要导出表架构,还要导出主键、外键、约束、索引、存储过程、用户定义的类型/函数。

另外,我不希望数据出现在这个T-SQL文件中。

有没有办法做到这一点?


可以通过SQL Server Management Studio将脚本生成到文件,步骤如下:

  • 右键单击要为其生成脚本(而不是表)的数据库,然后选择"任务-生成脚本"
  • 接下来,选择请求的表、视图、存储过程等(从选择特定的数据库对象中)
  • 单击高级-选择要编写脚本的数据类型
  • 单击"下一步"并完成
  • msdn生成脚本

    生成脚本时,有一个区域允许您从SQL Server 2008 R2中编写脚本、约束、键等。脚本下有一个高级选项:

    enter image description here


    氧化镁

    在照片中你可以看到。在"设置脚本选项"中,选择最后一个选项:单击右侧的"要编写脚本的数据类型",然后选择所需内容。这是您应该选择导出架构和数据的选项


    我编写了这个sp来自动创建包含所有内容的模式,pk、fk、分区、约束…

    重要!!执行前

    1
        CREATE TYPE TestTableType AS TABLE (ObjectID INT)

    这里是SP:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    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 = 'TableType')
            CREATE TYPE TableType AS TABLE (ObjectID INT)--drop type TableType

        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()
                ,inf.TABLE_SCHEMA
                ,inf.TABLE_NAME
                ,'
    '[''+inf.COLUMN_NAME+'']'' as COLUMN_NAME
                ,CAST(inf.ORDINAL_POSITION AS INT)
                ,inf.COLUMN_DEFAULT
                ,dobj.name AS ColumnDefaultName
                ,CASE WHEN inf.IS_NULLABLE = '
    'YES'' THEN 1 ELSE 0 END
                ,inf.DATA_TYPE
                ,case inf.CHARACTER_MAXIMUM_LENGTH when -1 then '
    'max'' else CAST(inf.CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
                ,CAST(inf.NUMERIC_PRECISION AS INT)
                ,CAST(inf.NUMERIC_SCALE AS INT)
                ,inf.DOMAIN_NAME
                ,inf.COLUMN_NAME + '
    ',''
                ,'
    ''' AS FieldDefinition
                --caso di viste, dà come campo identity ma nn dà i valori, quindi lo ignoro
                ,CASE WHEN ic.object_id IS not NULL and ic.seed_value is not null THEN 1 ELSE 0 END AS IdentityColumn--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 c.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
                ,cc.definition
                from (select schema_id,object_id,name from sys.views union all select schema_id,object_id,name from sys.tables)t
                    --sys.tables t
                join sys.schemas s on t.schema_id=s.schema_id
                JOIN sys.columns c ON  t.object_id=c.object_id --AND s.schema_id=c.schema_id
                LEFT JOIN sys.identity_columns ic ON t.object_id=ic.object_id AND c.column_id=ic.column_id
                left JOIN sys.types st ON st.system_type_id=c.system_type_id and st.principal_id=t.object_id--COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
                LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = c.default_object_id AND dobj.type = '
    'D''
                left join sys.computed_columns cc on t.object_id=cc.object_id and c.column_id=cc.column_id
                join INFORMATION_SCHEMA.COLUMNS inf on t.name=inf.TABLE_NAME
                                                   and s.name=inf.TABLE_SCHEMA
                                                   and c.name=inf.COLUMN_NAME
        WHERE inf.TABLE_NAME = @TableName and inf.TABLE_SCHEMA=@schema
        ORDER BY inf.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 ['' + @NewTableName+''_''+replace(name,@TableName,'''') + ''] 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 ['' + @NewTableName+''_''+replace(c.name,@TableName,'''') + ''] 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 TableType
                INSERT @t SELECT * FROM @PKObjectID
                DECLARE @u TableType
                INSERT @u SELECT * FROM @Uniques

                SET @SQL=
                '
                use '
    +@DBName+'
                SELECT distinct '
    ',CONSTRAINT '' + @NewTableName+''_''+replace(cco.name,@TableName,'''') + 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 TableType readonly,@u TableType 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

                ----------------------------------
                --SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH('')
                SET @script='use '+@DBName+' '+(SELECT FieldValue+'' FROM @MainDefinition FOR XML PATH(''))

                --declare @q    varchar(max)
                --set @q=(select replace((SELECT FieldValue FROM @MainDefinition FOR XML PATH('')),'</FieldValue>',''))
                --set @script=(select REPLACE(@q,'<FieldValue>',''))
                --drop type TableType
    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  
    -- ##############################################################################################################################################################################

    要执行它:

    1
    2
    3
    DECLARE @s VARCHAR(MAX)
    EXEC [util_ScriptTable]   'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,@s output
    SELECT @s


    您是否尝试过SQL Management Studio中的Generate Scripts选项(右键单击、任务、生成脚本)?这会产生您所说的"SQL文件"吗?