Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically retrieve the list of tables from SQL Server in dependency order?

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.

like image 985
Sako73 Avatar asked Oct 27 '25 15:10

Sako73


1 Answers

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?

like image 132
Ben Gribaudo Avatar answered Oct 29 '25 10:10

Ben Gribaudo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!