2

我有一个查询,它给了我列名、数据类型、最大长度、可空...

如果该列具有外键,我还需要知道该列所引用的表的名称。

这是我的查询

SELECT 
  c.name 'Column Name',
  t.Name 'Data type',
  c.max_length 'Max Length',
  c.is_nullable,
  ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM    
  sys.columns c
INNER JOIN 
  sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN 
  sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
  sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
  c.object_id = OBJECT_ID('Table_Name')
4

2 回答 2

2

感谢德瓦特,你让我走上了正确的道路。

这是将来参考的答案

SELECT
      [Column Name] = c.name
    , [Data type] = t.name
    , [Max Length] = c.max_length
    , c.is_nullable
    , [Primary Key] = ISNULL(i.is_primary_key, 0)
    , OBJECT_NAME(fkc.referenced_object_id)
FROM sys.columns c WITH(NOWAIT)
JOIN sys.types t WITH(NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
LEFT JOIN (
     SELECT i.[object_id], ic.column_id, i.is_primary_key
     FROM sys.indexes i WITH(NOWAIT)
     JOIN sys.index_columns ic WITH(NOWAIT) ON ic.[object_id] = i.[object_id] 
          AND i.index_id = ic.index_id
     WHERE i.is_primary_key = 1
) i ON c.[object_id] = i.[object_id] AND c.column_id = i.column_id
LEFT JOIN sys.foreign_key_columns fkc WITH(NOWAIT) ON fkc.parent_object_id = c.[object_id] 
     AND fkc.parent_column_id = c.column_id
WHERE c.[object_id] = OBJECT_ID('TableName')
于 2013-07-25T14:37:56.660 回答
1

试试这个——

SELECT
      [Column Name] = c.name
    , [Data type] = t.name
    , [Max Length] = c.max_length
    , c.is_nullable
    , [Primary Key] = ISNULL(i.is_primary_key, 0)
    , IsFK = ISNULL(fkc.parent_object_id / fkc.parent_object_id, 0)
FROM sys.columns c WITH(NOWAIT)
JOIN sys.types t WITH(NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
LEFT JOIN (
     SELECT i.[object_id], ic.column_id, i.is_primary_key
     FROM sys.indexes i WITH(NOWAIT)
     JOIN sys.index_columns ic WITH(NOWAIT) ON ic.[object_id] = i.[object_id] 
          AND i.index_id = ic.index_id
     WHERE i.is_primary_key = 1
) i ON c.[object_id] = i.[object_id] AND c.column_id = i.column_id
LEFT JOIN sys.foreign_key_columns fkc WITH(NOWAIT) ON fkc.parent_object_id = c.[object_id] 
     AND fkc.parent_column_id = c.column_id
WHERE c.[object_id] = OBJECT_ID('Table_Name')
于 2013-07-25T06:01:49.877 回答