如何从 sql server information_schema(元数据)中获取依赖表?

Posted

技术标签:

【中文标题】如何从 sql server information_schema(元数据)中获取依赖表?【英文标题】:How do I get dependent tables from sql server information schema (meta data)? 【发布时间】:2011-05-01 10:59:26 【问题描述】:

我需要知道哪些表中的哪些列是主键以及外键,以便我知道哪些表是依赖(关联/多对多关系)表。我从这样的查询开始,但它没有给我我需要的东西。

  --get all tables with primary keys with pk,fk in it. --not complete
SELECT
TC.TABLE_NAME, TC.CONSTRAINT_TYPE, CCU.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC left JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
ON TC.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND TC.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND
TC.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU ON CCU.CONSTRAINT_CATALOG = TC.CONSTRAINT_CATALOG AND
CCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA AND CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME

我需要更改它,以便我可以获得 pk+fk 列的表名和列名。帮助将不胜感激。

【问题讨论】:

【参考方案1】:

从这里:http://wiki.lessthandot.com/index.php/Find_all_Primary_and_Foreign_Keys_In_A_Database

SELECT TC.CONSTRAINT_SCHEMA + '.'+ TC.TABLE_NAME AS PRIMARYKEYTABLE
,TC.CONSTRAINT_NAME AS PRIMARYKEY,
CU.COLUMN_NAME AS [PRIMARY COLUMN Name]
,COALESCE(RC1.CONSTRAINT_NAME,'N/A') AS FOREIGNKEY,
COALESCE(CFU.Column_Name, 'N/A') AS [FOREIGN COLUMN Name]
,CASE WHEN TC2.TABLE_NAME IS NULL THEN 'N/A'
 ELSE TC.CONSTRAINT_SCHEMA + '.' + TC2.TABLE_NAME  END AS FOREIGNKEYTABLE
 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
 INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU ON TC.TABLE_NAME = CU.TABLE_NAME
 and TC.TABLE_SCHEMA = CU.TABLE_SCHEMA and Tc.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
 LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC1 ON TC.CONSTRAINT_NAME =RC1.UNIQUE_CONSTRAINT_NAME
 LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC2 ON TC2.CONSTRAINT_NAME =RC1.CONSTRAINT_NAME
 LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CFU ON RC1.CONSTRAINT_NAME  = CFU.CONSTRAINT_NAME
 WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY'
 ORDER BY TC.TABLE_NAME,TC.CONSTRAINT_NAME,RC1.CONSTRAINT_NAME

【讨论】:

我需要找到一个既是pk又是fk的列。 以上答案不是我想要的:我自己做的,贴在这里:pastebin.com/ty1gqmGw

以上是关于如何从 sql server information_schema(元数据)中获取依赖表?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 SQL Server DB 创建 SQL Server Express DB

如何从 C# 代码将 SQL Server CE 迁移到 SQL Server 2012 Express

cordova-plugin-network-information 1.3.0“网络信息”未检测到应用程序何时在线

如何使用 BCP 或 Sql Server Management Studio 从 Sql Server 中获取 BLOB 数据?

如何从 Azure SQL 迁移到 SQL Server? [复制]

如何从 sql server 将数据导入 mongodb?