2
现在我拥有列出所有引用表的代码,并且我可以从表中逐一计数引用。从所有引用表中计算对特定行的引用
查询1:
SELECT t.NAME AS TableWithForeignKey,
c.NAME AS ForeignKeyColumn
FROM sys.foreign_key_columns AS fk
INNER JOIN sys.tables AS t
ON fk.parent_object_id = t.object_id
INNER JOIN sys.columns AS c
ON fk.parent_object_id = c.object_id
AND fk.parent_column_id = c.column_id
WHERE fk.referenced_object_id = (
SELECT object_id
FROM sys.tables
WHERE NAME = 'MAIN_TABLE'
)
查询2:
SELECT COUNT(MAIN_ID)
FROM MAIN_TABLE
INNER JOIN REF_TABLE_1
ON MAIN_TABLE.ID = REF_TABLE_1.MAIN_ID
查询3:
SELECT COUNT(MAIN_ID)
FROM MAIN_TABLE
INNER JOIN REF_TABLE_2
ON MAIN_TABLE.ID = REF_TABLE_2.MAIN_ID
等
是否有可能把它在一个查询?
这是相当复杂的,它取决于(ouch)你想做什么。我认为这些资源可能会帮助您解决问题: http://www.databasejournal.com/features/mssql/article.php/3571026/Finding-Database-Object-Dependencies.htm http://beyondrelational.com/modules /2/blogs/28/posts/10399/tsql-lab-9-how-to-find-the-dependency-chain-of-a-database-object.aspx http://msdn.microsoft.com/en-我们/图书馆/ t9x04ed2.aspx希望这可以帮助 –
哦,这和http://blog.sqlauthority.com/2010/02/04/sql-server-get-the-list-of-object-dependencies-sp_depends-and- information_schema-routines-and-sys-dm_sql_referencing_entities/ –
我会看看这篇关于子查询的文章:http://allenbrowne.com/subquery-01.html它不清楚(对我来说)你的意思是什么REF_TABLE_1等。外部连接,子查询和联合,我会这么认为,或者你可以动态地构建你的SQL并使用sp_ExecuteSQL在单个表中获得结果? –