我正在尝试编写SQL查询以获取表的主键的完整规范。我可以编写一个查询来获取列,但我无法查询列的排序信息。例如,表定义为:
CREATE TABLE [dbo].[MyPrimaryKeyTable]( [MyKeyColumn] [int] NOT NULL, [SecondKeyColumn] [int] NOT NULL, [ThirdCol] [varchar](50) NOT NULL, [ForthCol] [varchar](10) NOT NULL )
GO
ALTER TABLE [dbo].[MyPrimaryKeyTable] ADD CONSTRAINT [PK_MyPrimaryKey] PRIMARY KEY CLUSTERED ([MyKeyColumn] ASC, [SecondKeyColumn] DESC, [ThirdCol] DESC)
GO
如果您使用查询:
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'MyPrimaryKeyTable'
然后我得到一组结果,显示表名和组成主键的三列(MyKeyColumn,SecondKeyColumn和ThirdCol),但没有信息说MyKeyColumn按升序排序,另外两个列作为键的一部分以降序排序。如何查询主键的列排序信息?
答案 0 :(得分:1)
这样的东西 - 您可以将OBJECT_NAME(o.parent_object_id)='tablename'添加到单个PK的位置。通过少量调整,它还可以为您提供所有索引的数据。
SELECT OBJECT_SCHEMA_NAME(o.parent_object_id) AS [Schema], OBJECT_NAME(o.parent_object_id) AS [Table], o.name AS PrimaryKey, ic.index_id, ic.key_ordinal, c.name AS ColumnName, t.name AS DataType, ic.is_descending_key
from sys.objects o
inner join sys.indexes i on i.object_id = o.parent_object_id and i.is_primary_key = 1
inner join sys.index_columns ic on ic.object_id = i.object_id and ic.index_id = i.index_id
inner join sys.columns c on c.object_id = o.parent_object_id and c.column_id = ic.column_id
inner join sys.types t ON t.user_type_id = c.user_type_id
where o.type = 'PK'
ORDER BY OBJECT_SCHEMA_NAME(o.parent_object_id), OBJECT_NAME(o.parent_object_id), ic.key_ordinal
更一般地说,使用MS的DMV通常会显示比INFORMATION_SCHEMA视图更多的信息,例如:用户数据类型&其他SQL Server特有的功能。