In SQL Server, how do I generate a CREATE TABLE statement for a given table?

前端 未结 16 2192
离开以前
离开以前 2020-11-22 11:34

I\'ve spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I\'m posting it here, since I think it might be useful to others. <

16条回答
  •  伪装坚强ぢ
    2020-11-22 11:54

    Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.

    declare @schema varchar(100), @table varchar(100)
    set @schema = 'dbo' -- set schema name here
    set @table = 'MyTable' -- set table name here
    declare @sql table(s varchar(1000), id int identity)
    
    -- create statement
    insert into  @sql(s) values ('create table [' + @table + '] (')
    
    -- column list
    insert into @sql(s)
    select 
        '  ['+column_name+'] ' + 
        data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
        case when exists ( 
            select id from syscolumns
            where object_name(id)=@table
            and name=column_name
            and columnproperty(id,name,'IsIdentity') = 1 
        ) then
            'IDENTITY(' + 
            cast(ident_seed(@table) as varchar) + ',' + 
            cast(ident_incr(@table) as varchar) + ')'
        else ''
        end + ' ' +
        ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
        coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
    
     from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
     order by ordinal_position
    
    -- primary key
    declare @pkname varchar(100)
    select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    where table_name = @table and constraint_type='PRIMARY KEY'
    
    if ( @pkname is not null ) begin
        insert into @sql(s) values('  PRIMARY KEY (')
        insert into @sql(s)
            select '   ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
            where constraint_name = @pkname
            order by ordinal_position
        -- remove trailing comma
        update @sql set s=left(s,len(s)-1) where id=@@identity
        insert into @sql(s) values ('  )')
    end
    else begin
        -- remove trailing comma
        update @sql set s=left(s,len(s)-1) where id=@@identity
    end
    
    -- closing bracket
    insert into @sql(s) values( ')' )
    
    -- result!
    select s from @sql order by id
    

提交回复
热议问题