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

前端 未结 16 2476
离开以前
离开以前 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:49

    I'm going to improve the answer by supporting partitioned tables:

    find partition scheme and partition key using below scritps:

    declare @partition_scheme varchar(100) = (
    select distinct ps.Name AS PartitionScheme
    from sys.indexes i  
    join sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id  
    join sys.partition_schemes ps on ps.data_space_id = i.data_space_id  
    where i.object_id = object_id('your table name')
    )
    print @partition_scheme
    
    declare @partition_column varchar(100) = (
    select 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)
    where t.object_id  = object_id('your table name')
    )
    print @partition_column
    

    then change the generation query by adding below line at the right place:

    + IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')
    

提交回复
热议问题