主键序号

时间:2016-10-13 16:51:28

标签: sql-server primary-key

有谁知道如何获取SQL Server表中包含主键的列的Ordinal_Position?

2 个答案:

答案 0 :(得分:0)

看看这个:https://msdn.microsoft.com/en-us/library/ms188348.aspx

查询列表,并将“TABLE_NAME”=设置为您获取序数位置后的表格。

SELECT ordinal_position
  FROM columns
 WHERE table_name = 'MYTABLE'

希望这有帮助!

答案 1 :(得分:0)

在SQL Server 2012中测试。这适用于特定列:

SELECT 
    KU.ORDINAL_POSITION   AS ORDINAL_POSITION
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' 
                                              AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
                                              AND ku.table_name = 'YourTable'
                                              AND column_name = 'YourColumn'

如果您不知道列名,则会为您提供主键

中的所有列
   SELECT KU.ORDINAL_POSITION AS ORDINAL_POSITION
    ,column_name AS ColumnName
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN 
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
                                            AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
                                            AND ku.table_name = 'yourTable'