1

我试图从 sys.indexes 表中获取特定表的所有列的列表以及数据类型和 is_primary_key 列。但我无法正确获取 is_primary_key 列。我希望 is_primary_key 仅针对作为表主键的列设置为 1。所有列都设置为 1

下面是我正在使用的查询

select distinct c.name,c.system_type_id,is_primary_key from sys.columns c 
   inner join  sys.tables t on c.object_id=t.object_id
   inner join sys.index_columns ic on ic.column_id=c.column_id 
   inner join sys.indexes i on i.index_id=ic.index_id
   and t.name='comp' and i.is_primary_key=1
4

2 回答 2

2

兑换

inner join sys.indexes i on i.index_id=ic.index_id

inner join sys.indexes i on i.index_id=ic.index_id and i.object_id=ic.object_id

的主键sys.indexes(object_id, index_id)。你有一个类似的错误sys.index_columns

于 2012-06-28T21:07:53.900 回答
1
select '['+name+']',system_type_id, case when primarykeyCol.column_id is null then 0 else 1 end primaryCol  from sys.columns c 
left join (select c.column_id from sys.indexes i  
inner join sys.index_columns ic on i.index_id = ic.index_id and i.is_primary_key = 1 and i.object_id = object_id(@srctablename) and  ic.object_id = object_id(@srctablename)
inner join sys.columns c on ic.column_id = c.column_id and c.object_id = object_id(@srctablename) 
) primarykeyCol on primarykeyCol.column_id = c.column_id 

where c.object_id = object_id(@srctablename)
于 2012-06-29T14:52:37.163 回答