How to list tables in their dependency order (based on foreign keys)?(如何按依赖顺序列出表(基于外键)?)
问题描述
这个问题最初是由@PrateekGupta 提出的
This question was originally asked by @PrateekGupta
@PrateekGupta 想对多个表执行批量插入操作.
表之间有外键关系.
如果在插入引用的表之前对具有外键的表执行 INSERT 操作,则操作可能会由于违反外键而失败.
@PrateekGupta wanted to perform bulk insert operation on multiple tables.
The tables have foreign key relationships between themselves.
If an INSERT operation is done on a table with a foreign key before the referenced table is being inserted to, the operation might fail due to violation of the foreign key.
根据它们的依赖关系在数据库中生成一个表列表.
没有依赖项(没有外键)的表将排在第一位.
仅在第 1 组表中具有依赖关系的表将排在第 2 位.
仅在第 1 组或第 2 组表中具有依赖关系的表将排在第 3 组.
等等……
Produce a list of tables within a database ordered according to their dependencies.
Tables with no dependencies (no foreign keys) will be 1st.
Tables with dependencies only in the 1st set of tables will be 2nd.
Tables with dependencies only in the 1st or 2nd sets of tables will be 3rd.
and so on...
推荐答案
example:
create table t1 (i int primary key,j int unique)
create table t2 (i int primary key references t1 (i));
create table t3 (i int,j int,primary key (i,j));
create table t4 (i int,j int, foreign key (i,j) references t3 (i,j));
create table t5 (i int references t1 (i),j int,foreign key (i,j) references t3 (i,j));
create table t6 (i int references t2 (i));
<小时>
with cte (lvl,object_id,name)
as
(
select 1
,object_id
,name
from sys.tables
where type_desc = 'USER_TABLE'
and is_ms_shipped = 0
union all
select cte.lvl + 1
,t.object_id
,t.name
from cte
join sys.tables as t
on exists
(
select null
from sys.foreign_keys as fk
where fk.parent_object_id = t.object_id
and fk.referenced_object_id = cte.object_id
)
and t.object_id <> cte.object_id
and cte.lvl < 30
where t.type_desc = 'USER_TABLE'
and t.is_ms_shipped = 0
)
select name
,max (lvl) as dependency_level
from cte
group by name
order by dependency_level
,name
;
这篇关于如何按依赖顺序列出表(基于外键)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何按依赖顺序列出表(基于外键)?
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
