使用生成的创建语句重复Sql Server表定义

时间:2014-04-21 06:56:37

标签: sql-server tsql

我需要将几个表定义从一个数据库复制到另一个数据库。我找到了一种为我需要的每个表生成create语句的方法。但是我不能执行生成的每个'create statement'。我希望以下脚本将重新创建与NEWDB数据库中的条件匹配的所有表。但事实并非如此。它总是只重建一个表而不是我需要的所有表。我不是sql专家,我相信我在这里遗漏了一些东西。

declare @sql varchar(8000)

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

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

-- this execute one table only regardless how many table in actual result set 
exec (@sql)

1 个答案:

答案 0 :(得分:2)

SSMS支持在2k8:

中编写所有架构(以及可选的数据作为INSERTS)的脚本

右键单击数据库,然后选择“任务” - >“生成脚本...”

选择所有表格或选择所需的表格,单击“下一步”。

...

请在此处查看答案:"Script all data from SQL Server database"

这比试图推销自己更容易。