0

我已经编写了获取 TableName、Columns、Precision 的查询,但是如何获取与表相关的外键和约束

    SELECT DISTINCT 
    QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema',
    QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table',
    C.NAME AS 'Column',
    T.NAME AS 'DataType',
    C.max_length,
    C.is_nullable,
    c.precision,
    c.scale

FROM SYS.COLUMNS C
INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0 
ORDER BY tb.[Name]

建议我

4

1 回答 1

0

试试这个

SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
And OBJECT_NAME(parent_object_id) = 'TableName'

或者你也可以试试这个(参考:http ://sqlmag.com/t-sql/summarize-all-constraints-table )

SELECT OBJECT_NAME(constid) 'Constraint Name',
  constid 'Constraint ID',
  CASE (status & 0xF)
    WHEN 1 THEN 'Primary Key'
    WHEN 2 THEN 'Unique'
    WHEN 3 THEN 'Foreign Key'
    WHEN 4 THEN 'Check'
    WHEN 5 THEN 'Default'
    ELSE 'Undefined'
  END 'Constraint Type',
  CASE (status & 0x30)
    WHEN 0x10 THEN 'Column'
    WHEN 0x20 THEN 'Table'
    ELSE 'N/A'
  END 'Level'
  FROM sysconstraints
  WHERE id=OBJECT_ID('TableName')

更多详情如下

通过引用这个问题SQL Server 2008-Get table constraints

您应该使用当前的 sys 目录视图(如果您使用的是 SQL Server 2005 或更高版本 - 不推荐使用 sysobjects 视图,应该避免使用) - 在此处查看有关目录视图的大量 MSDN SQL Server 联机丛书文档。

您可能会感兴趣的视图有很多:

  • sys.default_constraints对于列的默认约束
  • sys.check_constraints检查列上的约束
  • sys.key_constraints用于键约束(例如主键)
  • sys.foreign_keys对于外键关系

还有更多 - 看看吧!

您可以查询并加入这些视图以获取所需的信息 - 例如,这将列出表、列和在它们上定义的所有默认约束:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
于 2013-09-19T10:59:00.777 回答