我们能否有一个 SQL 查询来列出数据库中任何过程中未引用的所有表?
Can we have a SQL query that lists all the tables that are not referred in any procedures within a database?
SQL 查询将列出数据库中未在任何过程中使用的所有表。
select name into #temp from sys.tables
update #temp
set name = CONCAT('%',name,'%')
select name into #temp2 from #temp
delete from #temp2
insert into #temp2
SELECT T.Name FROM sys.procedures SP, #temp T
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE T.name
SELECT * FROM #temp
EXCEPT
SELECT * FROM #temp2
drop table #temp
drop table #temp2
比解析过程主体更干净恕我直言:
SELECT s.name, t.name
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
WHERE NOT EXISTS
(
SELECT 1
FROM sys.sql_expression_dependencies AS d
INNER JOIN sys.procedures AS p
ON d.referencing_id = p.[object_id]
WHERE d.referenced_id = t.[object_id]
);
请注意,这不会捕获将 table 名称作为参数或动态构建它们并作为动态执行的存储过程 SQL。
SQL 查询将列出数据库中未在任何过程中使用的所有表。
select name into #temp from sys.tables
update #temp
set name = CONCAT('%',name,'%')
select name into #temp2 from #temp
delete from #temp2
insert into #temp2
SELECT T.Name FROM sys.procedures SP, #temp T
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE T.name
SELECT * FROM #temp
EXCEPT
SELECT * FROM #temp2
drop table #temp
drop table #temp2
比解析过程主体更干净恕我直言:
SELECT s.name, t.name
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
WHERE NOT EXISTS
(
SELECT 1
FROM sys.sql_expression_dependencies AS d
INNER JOIN sys.procedures AS p
ON d.referencing_id = p.[object_id]
WHERE d.referenced_id = t.[object_id]
);
请注意,这不会捕获将 table 名称作为参数或动态构建它们并作为动态执行的存储过程 SQL。