gpt4 book ai didi

SQL-Server查询自身结果

转载 作者:行者123 更新时间:2023-12-03 18:46:22 25 4
gpt4 key购买 nike

我正在尝试确定从我的数据库中删除表的风险。

数据库很大,包含数百个表。

我有一个返回与表关联的外键的查询。所以我可以给它提供我想删除的表名,它会告诉我哪些表依赖于它拥有的列。因此,我还必须删除返回的表。

我的问题来了,因为我需要删除这些表,所以我希望看到任何其他依赖于初始结果的表。

因此,我相信我需要我的查询使用上次运行的结果循环调用自身,直到没有更多唯一结果。

这可能吗?有更简单的方法吗?

编辑:这是查询:

SELECT
PK.TABLE_NAME AS PrimaryTable,
FK.TABLE_NAME AS ForeignTable,
PT.COLUMN_NAME AS PrimaryColumn,
CU.COLUMN_NAME AS ForeignColumn,
C.CONSTRAINT_NAME AS ConstraintName
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
WHERE PK.TABLE_NAME IN
('Table1','Table2')
ORDER BY
1,2,3,4

最佳答案

您可以尝试使用 CTE。我发现在最终 select 语句上编写实际的 where 子句更容易,但如果性能是个问题,我建议您在 relations CTE (在 UNION ALL 之上)

CTE 选择声明

;WITH q AS (
SELECT
PK.TABLE_NAME AS PrimaryTable,
FK.TABLE_NAME AS ForeignTable,
PT.COLUMN_NAME AS PrimaryColumn,
CU.COLUMN_NAME AS ForeignColumn,
C.CONSTRAINT_NAME AS ConstraintName
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
)
, Relations AS (
SELECT PrimaryTable AS Root
, *
FROM q
UNION ALL
SELECT r.Root
, q.PrimaryTable
, q.ForeignTable
, q.PrimaryColumn
, q.ForeignColumn
, q.ConstraintName
FROM q
INNER JOIN Relations r ON r.ForeignTable = q.PrimaryTable
)
SELECT *
FROM Relations
WHERE Root IN ('Table1','Table2')
ORDER BY
1,2,3,4

关于SQL-Server查询自身结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14686761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com