日期:2014-05-17  浏览次数:21187 次

C# 获得sql server中表的创建语句
最近在做一个数据库转移的小工具,当把原先数据库(A)中的表全部转移到另外一个数据库(B)中时,首先需要自动建表,就是将A库中的所有表在B库中自动生成。
但现在不知道如何获得A库中所有表的create语句,求大神帮帮忙。
C#获得create语句 SQL?Server数据库表迁移 C#复制数据库

------解决方案--------------------
--如果不存在自动递增ID,可以这么删除
select 'truncate table '+name
from sys.tables 
--否先删除数据,再把自动递增ID回归到1
select 'delete '+name
from sys.tables 


DBCC CHECKIDENT(表名, RESEED, 1)

------解决方案--------------------
其实是好是先清空数据的所有表数据,这样最好,因为存在约束关系,新建表存在先后顺序,还要做约束比较麻烦。

清空数据比较简单,也很好检查。

如果一定要用脚本生成新的数据表,也有办法。参考:


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