2010-02-26

Common Table Expression for Database Structure

When copying data from one database to another, breaking constraints is always a problem. If you do not insert data in a certain sequence, you will get foreign key violations. So I tried to work out a CTE that starts with all tables that have no foreign keys, then the tables referencing them, then the once referencing them again, and so on… So came up with this:

WITH CTE (name,object_id, lvl)
AS
(
    select name, object_id, 0 AS lvl from sys.tables
    where object_id NOT IN (select parent_object_id from sys.foreign_keys)
   
UNION ALL

    select tbls.name, tbls.object_id , lvl + 1 from sys.tables tbls
    join sys.foreign_keys keys on tbls.object_id = keys.parent_object_id
    join CTE on CTE.object_id =  keys.referenced_object_id
)
SELECT * FROM CTE
OPTION (MAXRECURSION 10000)

Note that this will not work if you have self-referencing tables, ie. tables that have a foreign key pointing to its own primary key. Also the same tables may appear many times because they reference the same tables. And also if the same table have many foreign keys it will appear many times.

The conclusion is that this does not solve my problem, but it was fun to create the CTE anyway.

No comments:

Post a Comment