[转]mssql中得到库里所有的表名,以及表的结构(列名和数据类型)

本文转自:http://kyle.itpub.net/post/1626/8891

原文如下:
----------------
--得到数据库中所有的表名,以及表对应的字段,字段对应的类型,存放在#magic临时表里
if exists (select * from tempdb..sysobjects where name like '#magic%')
drop table #magic
go
select a.name name,b.name col,c.name type
into #magic
from sysobjects a,syscolumns b,systypes c
where a.xtype = 'U'
and a.id = b.id
and b.xtype = c.xtype
and b.xusertype = c.xusertype

--将结果加工
select (case when tmp3.no=1 then tmp3.name else ' ' end) name,col,type
from
(select top 100000000 name
 ,(select count(1) from #magic tmp1
   where tmp1.name=tmp2.name
   and tmp1.col<=tmp2.col) as no,col,type
   from #magic tmp2
   order by name,col,type)
tmp3

 

--下面一种方法转自csdn
SELECT
(case when a.colorder=1 then d.name else '' end) N'表名',
a.colorder N'字段序号',
a.name N'字段名',
(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) N'标识',
(case when (SELECT count(*)
FROM sysobjects
WHERE (name in
(SELECT name
FROM sysindexes
WHERE (id = a.id) AND (indid in
(SELECT indid
FROM sysindexkeys
WHERE (id = a.id) AND (colid in
(SELECT colid
FROM syscolumns
WHERE (id = a.id) AND (name = a.name))))))) AND
(xtype = 'PK'))>0 then '√' else '' end) N'主键',
b.name N'类型',
a.length N'占用字节数',
COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'长度',
isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小数位数',
(case when a.isnullable=1 then '√'else '' end) N'允许空',
isnull(e.text,'') N'默认值',
isnull(g.[value],'') AS N'字段说明'
--into ##tx

FROM syscolumns a left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id=g.id AND a.colid = g.smallid
order by object_name(a.id),a.colorder

posted on 2007-08-29 11:44  freeliver54  阅读(1199)  评论(0编辑  收藏  举报

导航