好的,我知道,非常老的话题 - 但我在其他任何地方都找不到足够的答案,所以我以 IAmTimCorey 的答案为起点进行了研究。这给出了以下结果:
SELECT sc.colid,
Substring(sc.NAME, 1, 40) 'column name',
Substring(st.NAME, 1, 40) 'type',
sc.length,
sc.prec,
sc.status,
( CASE
WHEN ( sc.status & 8 ) != 0 THEN 'Y'
ELSE 'N'
END ) AS 'nullable',
( CASE
WHEN ( sc.status & 128 ) != 0 THEN 'Y'
ELSE 'N'
END ) AS 'identity'
FROM tempdb..syscolumns sc
INNER JOIN tempdb..sysobjects so
ON sc.id = so.id
INNER JOIN systypes st
ON st.type = sc.type
AND st.usertype = sc.usertype
WHERE so.NAME = 'test'
ORDER BY sc.colid
例子:
1> create table tempdb..test(id numeric (15,0) identity, string varchar(40), num numeric(15,0) not null, dt datetime, flt float)
2> go
1> select sc.colid, substring(sc.name, 1, 40) 'column name', substring(st.name, 1, 40) 'type', sc.length, sc.prec, sc.status, (case when (sc.status & 8) != 0 then 'Y' else 'N' end) as nullable, (case when (sc.status & 128) != 0 then 'Y' else 'N' end) as ident from tempdb..syscolumns sc inner join tempdb..sysobjects so on sc.id = so.id inner join systypes st on st.type = sc.type and st.usertype = sc.usertype where so.name = 'test' order by sc.colid
2> go
colid column name type length prec status nullable ident
------ ---------------------------------------- ---------------------------------------- ----------- ---- ------ -------- -----
1 id numeric 8 15 128 N Y
2 string varchar 40 NULL 0 N N
3 num numeric 8 15 0 N N
4 dt datetime 8 NULL 0 N N
5 flt float 8 NULL 0 N N
(5 rows affected)
1>
备注:
- 可空列的检测源自 Sybase 文档,但由于我不知道的原因,tempdb..syscolumns 中状态的第 3 位没有相应更改,请参见示例中的第 num 列。这就是为什么我无论如何都添加了列状态。对于身份(第 7 位),事情按预期工作。任何解释将不胜感激。
- 使用 isql 时,以足够的宽度开始(例如 -w160)
- syscolumns.name 和 systypes.name 的默认列宽非常大,因此我使用的是 substring(....)。如果您的列名不合适,请调整复制的字符数(substring() 的最后一个参数)。
- 通过从表名中省略“tempdb..”,此查询也适用于普通的非 tempdb 表,以防查询优于使用 sp_xxx 命令。