sp_columns按主键列

时间:2017-06-06 07:27:42

标签: sql-server

exec sp_columns 'table'返回COLUMN_NAMES列中的所有列名:

TABLE_QUALIFIER     TABLE_OWNER     TABLE_NAME          COLUMN_NAME             DATA_TYPE   TYPE_NAME       PRECISION   LENGTH  SCALE   RADIX   NULLABLE    REMARKS     COLUMN_DEF  SQL_DATA_TYPE   SQL_DATETIME_SUB    CHAR_OCTET_LENGTH   ORDINAL_POSITION    IS_NULLABLE SS_DATA_TYPE
transdata           dbo             Flow                Distance                6           float           15          8       NULL    10      1           NULL        NULL        6               NULL                NULL                9                   YES         109
transdata           dbo             Flow                FlowID                  4           int identity    10          4       0       10      0           NULL        NULL        4               NULL                NULL                10                  NO          56

我想要的是COLUMN_NAMES首先显示主键列,然后是非主键列。 sp_columns是否可以实现这一点?

按主键排序应解决此问题,但sp_columns不会返回主键信息。

TABLE_QUALIFIER     TABLE_OWNER     TABLE_NAME          COLUMN_NAME             DATA_TYPE   TYPE_NAME       PRECISION   LENGTH  SCALE   RADIX   NULLABLE    REMARKS     COLUMN_DEF  SQL_DATA_TYPE   SQL_DATETIME_SUB    CHAR_OCTET_LENGTH   ORDINAL_POSITION    IS_NULLABLE SS_DATA_TYPE
transdata           dbo             Flow                FlowID                  4           int identity    10          4       0       10      0           NULL        NULL        4               NULL                NULL                10                  NO          56
transdata           dbo             Flow                Distance                6           float           15          8       NULL    10      1           NULL        NULL        6               NULL                NULL                9                   YES         109

1 个答案:

答案 0 :(得分:1)

您的任务太复杂,不能简单执行SP。 您应该自己编写查询(IC列为空,如果列不是PK):

SELECT 
    TableName   = OBJECT_NAME(C.object_id), 
    ColumnName  = C.name,
    ColumnType  = TYPE_NAME(C.system_type_Id), 
    IsPK        = IIF(IC.object_id IS NULL, 0, 1)
FROM sys.columns                C
LEFT JOIN sys.key_constraints   KC  ON KC.parent_object_id = C.object_id AND kc.type = 'PK'
LEFT JOIN sys.index_columns     IC  ON KC.parent_object_id = IC.object_id  AND KC.unique_index_id = IC.index_id AND IC.column_id = C.column_id
WHERE C.object_id = OBJECT_ID(@TableName)
ORDER BY ...

以下是类似的问题:How can I select the primary key columns from a table?