简体   繁体   中英

Sql Server - Get Full Primary Key of table including column sort orders via a sql query

I am trying write a SQL query to get the full specification of the primary key of a table. I can write a query to get the columns involved but I cannot query back the sort information of the columns. For example the table defined as:

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

If you use the query:

SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'MyPrimaryKeyTable'

Then I get back a set of results that show the table name and the three columns that make up the primary key (MyKeyColumn, SecondKeyColumn and ThirdCol) but there is no information to say that the MyKeyColumn was sorted ascending and the other two columns are sorted descending as part of the key. How do I query the column sorting information for the primary key?

Something like this - you can add OBJECT_NAME(o.parent_object_id) = 'tablename' into the where for a single PK. With a small amount of tweaking it can give you the data for all indexes too.

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

On a more general note, using MS's DMV's will generally reveal more information than the INFORMATION_SCHEMA views, eg user data types & other SQL Server-specific features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM