如何获取表名,外键和约束

时间:2013-09-19 10:51:32

标签: sql-server tsql

我已经编写了查询,其中我得到了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]

Suugest me

1 个答案:

答案 0 :(得分: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联机丛书文档。< / p>

您可能会对以下几种观点感兴趣:

  • 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