计算外键列的数量,忽略系统表,针对每个表名显示

时间:2014-07-21 07:18:48

标签: sql sql-server

我们使用foll。查询计算否。数据库中的主键列: -

SELECT t.name,is_primary_key
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id AND 

t.type = 'U'
LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T.

[object_id]
WHERE (EP.class_desc IS NULL 
OR (EP.class_desc <> 'OBJECT_OR_COLUMN'
    AND EP.[name] <> 'microsoft_database_tools_support'))

它会忽略系统表中的列。

现在我们要查询数据库中的外键数。此应忽略系统表并显示每个表名的计数。这可能吗?

下面的查询返回db中的所有外键,但是我想忽略systabes ..就像上面的查询一样。

SELECT COUNT(*) AS 'FOREIGN_KEY_CONSTRAINT'
FROM sys.objects
WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT')

3 个答案:

答案 0 :(得分:1)

运行以下查询。这将用于所需目的:

SELECT KC.Column_Name, t.Table_Name, tc.Constraint_Name FROM information_schema.table_constraints tc
LEFT JOIN information_schema.tables t ON tc.Table_Name = t.Table_Name
LEFT JOIN information_schema.KEY_COLUMN_USAGE kc ON kc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE constraint_type = 'FOREIGN KEY' AND TABLE_TYPE = 'BASE TABLE'

答案 1 :(得分:0)

这个?

SELECT DISTINCT A.COLUMN_NAME,
                B.CONSTRAINT_TYPE
FROM   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE A
       JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B
         ON A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
ORDER  BY CONSTRAINT_TYPE ASC 

如果需要,请使用where子句

答案 2 :(得分:0)

试试这个 -

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME

SOURCE