[英]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. 我正在尝试编写一个SQL查询来获取表主键的完整规范。 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. 然后,我得到了一组结果,这些结果显示了表名以及组成主键的三列(MyKeyColumn,SecondKeyColumn和ThirdCol),但是没有信息说MyKeyColumn是升序排列的,而其他两列是排序的作为钥匙的一部分下降。 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. 这样的事情-您可以将OBJECT_NAME(o.parent_object_id)='tablename'添加到单个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. 一般而言,使用MS的DMV通常会显示比INFORMATION_SCHEMA视图更多的信息,例如,用户数据类型和其他特定于SQL Server的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.