4

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.

1
  • You're building a lot of infrastructure when you could not allow user defined tables (nevermind constraints). Another alternative to consider would be EAV Commented Nov 11, 2011 at 18:47

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure it CAN be done? It is legal in SQL to have circular references, so it is quite commong that there is no perfect order. Optional null values allow inserts (followed by an update). But tree relations are not a uni directional graph in most scenarios.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.