关闭

【SQLSERVER】获取建表DDL(+主键)

标签: sql server
116人阅读 评论(0) 收藏 举报
分类:
--获取建表DDL(+主键)
declare @tabname varchar(50)
set @tabname='testbzm'--表名

if ( object_id('tempdb.dbo.#t') is not null)
begin
DROP TABLE #t
end

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 
    TABLE_DDL
into #t 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=@tabname

select 'USE '+db_name() +CHAR(13) +'GO' + CHAR(13) +
(--区别有主键和没主键
case when (select count(a.constraint_type)
from information_schema.table_constraints a 
inner join information_schema.constraint_column_usage b
on a.constraint_name = b.constraint_name
where a.constraint_type = 'PRIMARY KEY'--主键 
and a.table_name = @tabname)=1 then
replace(table_ddl,', )ALTER TABLE',')'+CHAR(13)+'ALTER TABLE')
else SUBSTRING(table_ddl,1,len(table_ddl)-3)+')' end
) from #t

--drop table #t
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:36583次
    • 积分:1705
    • 等级:
    • 排名:千里之外
    • 原创:140篇
    • 转载:8篇
    • 译文:0篇
    • 评论:0条