日期:2014-05-18  浏览次数:20624 次

如何使用SQL语句导出表结构脚本?
如何使用SQL语句导出表结构脚本?

强调:必须使用SQL脚本,我想把这SQL语句写入我的程序中。


谢谢

------解决方案--------------------
--老大写的SQL

SELECT TableName=o.name,OWNER=USER_NAME(o.uid),TableDescription=ISNULL(ptb.value,N ' '),
FieldId=c.colid,FieldName=c.name,
FieldType=QUOTENAME(t.name)
+CASE
WHEN t.name IN (N 'decimal ',N 'numeric ')
THEN N '( '+CAST(c.prec as varchar)+N ', '+CAST(c.scale as varchar)+N ') '
WHEN t.name=N 'float '
OR t.name like N '%char '
OR t.name like N '%binary '
THEN N '( '+CAST(c.prec as varchar)+N ') '
ELSE N ' ' END
+CASE WHEN c.isnullable=1 THEN N ' ' ELSE N ' NOT ' END+N ' NULL ',
FieldDescription=ISNULL(pfd.value, ' '),
DefileLength=c.length,
FieldDefault=ISNULL(df.text,N ' '),
IsIDENTITY=COLUMNPROPERTY(o.id,c.name,N 'IsIdentity '),
IsComputed=COLUMNPROPERTY(o.id,c.name,N 'IsComputed '),
IsROWGUID=COLUMNPROPERTY(o.id,c.name,N 'IsRowGuidCol '),
IsPrimaryKey=CASE WHEN opk.xtype IS NULL THEN 0 ELSE 1 END
FROM sysobjects o
JOIN syscolumns c
ON c.id=o.id
AND OBJECTPROPERTY(o.id,N 'IsUserTable ')=1
JOIN systypes t
ON t.xusertype=c.xusertype
LEFT JOIN syscomments df
ON df.id=c.cdefault
LEFT JOIN sysproperties ptb
ON ptb.id=o.id and ptb.smallid=0
LEFT JOIN sysproperties pfd
ON pfd.id=o.id and pfd.smallid=c.colid
LEFT JOIN sysindexkeys idxk
ON idxk.id=o.id
AND idxk.colid=c.colid
LEFT JOIN sysindexes idx
ON idx.indid=idxk.indid
AND idx.id=idxk.id
AND idx.indid NOT IN(0,255)
LEFT JOIN sysobjects opk
ON opk.parent_obj=o.id
AND opk.name=idx.name
AND OBJECTPROPERTY(opk.id,N 'IsPrimaryKey ')=1
ORDER BY o.name,c.colid
------解决方案--------------------
SELECT
TableName=o.name,
--OWNER=USER_NAME(o.uid),
TableDescription=ISNULL(ptb.value,N ' '),
FieldId=c.column_id,FieldName=c.name,
FieldType=QUOTENAME(t.name)
+CASE
WHEN t.name IN (N 'decimal ',N 'numeric ')
THEN N '( '+CAST(c.precision as varchar)+N ', '+CAST(c.scale as varchar)+N ') '
WHEN t.name=N 'float '
OR t.name like N '%char '
OR t.name like N '%binary '
THEN N '( '+CAST(c.precision as varchar)+N ') '
ELSE N ' ' END
+CASE WHEN c.is_nullable=1 THEN N ' ' ELSE N ' NOT ' END+N ' NULL ',
FieldDescription=ISNULL(pfd.value, ' '),
DefileLength=c.max_length,
FieldDefault=ISNULL(df.text,N ' '),
IsIDENTITY=COLUMNPROPERTY(o.object_id,c.name,N 'IsIdentity '),
IsComputed=COLUMNPROPERTY(o.object_id,c.name,N 'IsComputed '),
IsROWGUID=COLUMNPROPERTY(o.object_id,c.name,N 'IsRowGuidCol '),
IsPrimaryKey=CASE WHEN opk.type = 'pk ' THEN 0 ELSE 1 END
FROM sys.objects o
JOIN sys.columns c
ON c.object_id=o.object_id
AND OBJECTPROPERTY(o.object_id,N 'IsUserTable ')=1
JOIN sys.types t
ON t.user_type_id=c.user_type_id
LEFT JOIN sys.syscomments df
ON df.id=c.default_object_id
LEFT JOIN sys.extended_properties ptb
ON ptb.major_id = o.object_id
and ptb.minor_id=0
LEFT JOIN sys.extended_properties pfd
ON pfd.major_id=o.object_id and pfd.minor_id=c.column_id
LEFT JOIN sys.sysindexkeys idxk
ON idxk.id=o.obje