Manek
Manek

Reputation: 568

Get all tables programatically in a DB w.r.t relation

I am using a relational tables. On a button click i have to retrieve the all the tables in my database in such a way that all the Master tables are coming at the Top.( i.e Generate Scripts from the frontend) and save them onto a text file.

Back Ground purpose: I need to generate script for all the tables in the order and while executing the generated script Foreign key Constraint error will not occur.So I need to get table in the order of relations.

How can I retrieve the table in that way?

Upvotes: 2

Views: 255

Answers (1)

John Gathogo
John Gathogo

Reputation: 4655

If you use SQL Server Management Studio:

Right click [Your DB] -> Tasks -> Generate Scripts -> Next -> Next -> [Select Tables] Next -> ... all the way to the end,

the wizard should be able to create an intelligent scripts that creates dependent objects first.

EDITED (Oct 18, 2011):

If you generate your scripts from the output of the following query, you should have to worry about foreign key dependencies giving you problems:

;with tcte(tid, tname, lvl) 
as
(
select st.object_id, st.name, 0 
from sys.tables st left join sys.foreign_keys sfk on sfk.parent_object_id = st.object_id 
where sfk.name is null

union all

select st.object_id, st.name, 1 
from sys.tables st left join sys.foreign_keys sfk on sfk.parent_object_id = st.object_id 
where sfk.parent_object_id = sfk.referenced_object_id

union all

select st.object_id as tid, st.name, tcte.lvl + 1 
from sys.tables st inner join sys.foreign_keys sfk on sfk.parent_object_id = st.object_id 
inner join tcte on tcte.tid = sfk.referenced_object_id
where tcte.tid <> sfk.parent_object_id
)

select tname, max(lvl) lvl from tcte group by tname order by lvl

Upvotes: 3

Related Questions