-- ========================================================================== -- Description: Get the load levels by tracing foreign keys in the database. -- License: Creative Commons (Free / Public Domain) -- Rights: This work (Linchpin People LLC Database Load Levels Function, -- by W. Kevin Hazzard), identified by Linchpin People LLC, is -- free of known copyright restrictions. -- Warranties: This code comes with no implicit or explicit warranties. -- Linchpin People LLC and W. Kevin Hazzard are not responsible -- for the use of this work or its derivatives. -- ========================================================================== CREATE FUNCTION [dbo].[LoadLevels]() RETURNS @results TABLE ( [SchemaName] SYSNAME, [TableName] SYSNAME, [LoadLevel] INT ) AS BEGIN WITH [key_info] AS ( SELECT [parent_object_id] AS [from_table_id], [referenced_object_id] AS [to_table_id] FROM [sys].[foreign_keys] WHERE [parent_object_id] <> [referenced_object_id] AND [is_disabled] = 0 ), [level_info] AS ( SELECT -- anchor part [st].[object_id] AS [to_table_id], 0 AS [LoadLevel] FROM [sys].[tables] AS [st] LEFT OUTER JOIN [key_info] AS [ki] ON [st].[object_id] = [ki].[from_table_id] WHERE [ki].[from_table_id] IS NULL UNION ALL SELECT -- recursive part [ki].[from_table_id], [li].[LoadLevel] + 1 FROM [key_info] AS [ki] INNER JOIN [level_info] AS [li] ON [ki].[to_table_id] = [li].[to_table_id] ) INSERT @results SELECT OBJECT_SCHEMA_NAME([to_table_id]) AS [SchemaName], OBJECT_NAME([to_table_id]) AS [TableName], MAX([LoadLevel]) AS [LoadLevel] FROM [level_info] GROUP BY [to_table_id]; RETURN END GO
Via.