I am working with SQL Server 2008 R2. I want to query a database and retrieve all user defined tables (easy enough, SELECT Name FROM sys.tables), but I want it to be ordered so that if insert statements were executed in that order, they would not run into foreign key constraints.
In other words, I want the list of tables sorted by dependencies so that the highest level tables (i.e. the ones that had no dependencies) are before those that rely on them.
What is the most efficient way to query this?
Thanks for any help.
Does the ''top-down hierarchy'' query discussed on http://www.jasinskionline.com/technicalwiki/Default.aspx?Page=List-Tables-in-Dependency-Order-SQL-Server&NS=&AspxAutoDetectCookieSupport=1 produce the list you're looking for?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With