Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created September 2, 2015 07:45
Show Gist options
  • Select an option

  • Save ststeiger/1082d069dcbe30021473 to your computer and use it in GitHub Desktop.

Select an option

Save ststeiger/1082d069dcbe30021473 to your computer and use it in GitHub Desktop.
View to insert table by dependency
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'dbo.V_DEV_InsertDataDependency'))
DROP VIEW dbo.V_DEV_InsertDataDependency
GO
CREATE VIEW dbo.V_DEV_InsertDataDependency
AS
WITH Fkeys AS
(
SELECT DISTINCT
OnTable = OnTable.name
,AgainstTable = AgainstTable.name
FROM sysforeignkeys fk
INNER JOIN sysobjects onTable
ON fk.fkeyid = onTable.id
INNER JOIN sysobjects againstTable
ON fk.rkeyid = againstTable.id
WHERE 1=1
AND AgainstTable.TYPE = 'U'
AND OnTable.TYPE = 'U'
-- ignore self joins; they cause an infinite recursion
AND OnTable.Name <> AgainstTable.Name
)
,MyData AS
(
SELECT
OnTable = o.name
,AgainstTable = FKeys.againstTable
FROM sys.objects AS o
LEFT JOIN FKeys
ON o.name = FKeys.onTable
WHERE (1=1)
AND o.type = 'U'
AND o.name NOT LIKE 'sys%'
)
,MyRecursion AS
(
-- base case
SELECT
TableName = OnTable
,Lvl = 1
FROM MyData
WHERE 1=1
AND AgainstTable IS NULL
-- recursive case
UNION ALL
SELECT
TableName = OnTable
,Lvl = r.Lvl + 1
FROM MyData AS d
INNER JOIN MyRecursion AS r
ON d.AgainstTable = r.TableName
)
SELECT TOP 999999999999999999
MAX(Lvl) AS Lvl
,TableName
FROM MyRecursion
GROUP BY TableName
ORDER BY lvl, TableName
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment