获取所有表键的类型

时间:2011-11-01 18:12:30

标签: sql-server sql-server-2000

我已经设法将各种示例中的查询拼凑在一起以获取所有表键:

select tbl.name,idx.name as indexname,t1.*,col.name as colname
from dbo.sysindexkeys as t1
LEFT JOIN dbo.sysindexes as idx on (t1.id=idx.id and t1.indid=idx.indid)
LEFT JOIN dbo.syscolumns as col on (col.id=t1.id and col.colid=t1.colid)
LEFT JOIN dbo.sysobjects as tbl on (idx.id=tbl.id)
ORDER BY tbl.name,idx.name,t1.keyno

我唯一需要的是键的类型,据我所知应该是PKUQD(目前不关心外键) 。我似乎需要再次加入sysobjects以获取xtype列,但我无法找出正确的联接方式。

基于this answer我试过

select tbl.name,idx.name as indexname,s2.xtype,t1.*,col.name as colname
from dbo.sysindexkeys as t1
LEFT JOIN dbo.sysindexes as idx on (t1.id=idx.id and t1.indid=idx.indid)
JOIN sysobjects s2 on s2.parent_obj = t1.id
LEFT JOIN dbo.syscolumns as col on (col.id=t1.id and col.colid=t1.colid)
LEFT JOIN dbo.sysobjects as tbl on (idx.id=tbl.id)
ORDER BY tbl.name,idx.name,t1.keyno

但这会导致每个索引列有多个记录并且具有不同的xtypes。我希望每个索引列有一行(如果索引在三列上,那么应该有三行)都具有正确的xtype。我需要改变什么?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用status的{​​{1}}来确定密钥类型。查询可以是以下

sysindexes

我希望这可以在您当前使用的复古版SQL Server(SQL Server 2000)中使用。

答案 1 :(得分:1)

我进入了原始的sql语句并让它从xtype表返回sysobjects索引:

select tbl.name,idx.name as indexname,t1.*,col.name as colname, tbl2.xtype
from dbo.sysindexkeys as t1
LEFT JOIN dbo.sysindexes as idx on (t1.id=idx.id and t1.indid=idx.indid)
LEFT JOIN dbo.syscolumns as col on (col.id=t1.id and col.colid=t1.colid)
LEFT JOIN dbo.sysobjects as tbl on (idx.id=tbl.id)
JOIN dbo.sysobjects AS tbl2 ON (idx.id = tbl2.parent_obj) AND (idx.name = tbl2.name)
ORDER BY tbl.name,idx.name,t1.keyno

idx.id是索引所关联的表的id。 sysobjects表中没有任何内容,除了名称字段与sysindexes表中的内容匹配,因此必须加入该表。几乎做了另一个左连接,但是当我这样做时,我从索引表中获得了未在sysobjects表中列出的统计对象的行。

编辑: 我回过头来看看如何获​​取您正在寻找的信息并提出以下SQL语句:

SELECT name, indexname, id, indid, colid, keyno, colname, 
    ISNULL(xtype, CASE WHEN is_index = 1 THEN 'IX' WHEN status&2 <> 0 THEN 'UQ' ELSE xtype END) as xtype
FROM 
(select TOP 100 PERCENT
    tbl.name,
    idx.name as indexname,
    t1.*,
    col.name as colname, 
    idx.status, 
    CAST(CASE WHEN (idx.status=0 OR idx.status&5<>0) THEN 1 ELSE 0 END AS bit) AS is_index,
    CAST(CASE WHEN idx.status&64<>0 THEN 1 ELSE 0 END AS bit) AS is_statistic,
    tbl2.xtype
from dbo.sysindexkeys as t1
LEFT JOIN dbo.sysindexes as idx on (t1.id=idx.id and t1.indid=idx.indid)
LEFT JOIN dbo.syscolumns as col on (col.id=t1.id and col.colid=t1.colid)
LEFT JOIN dbo.sysobjects as tbl on (idx.id=tbl.id)
LEFT JOIN dbo.sysobjects AS tbl2 ON (idx.id = tbl2.parent_obj) AND (idx.name = tbl2.name)
ORDER BY tbl.name,idx.name,t1.keyno) AS dts
WHERE is_statistic = 0

我不确定如何显示'D'类型,因为它们不在sysindexkeys表中。