SQLServer: How to sort table names ordered by their foreign key dependency

前端 未结 4 1397
后悔当初
后悔当初 2020-12-23 22:39

The following SQL separates tables according to their relationship. The problem is with the tables that sort under the 3000 series. Tables that are part of foreign keys and

4条回答
  •  时光说笑
    2020-12-23 23:04

    Thank you for a working solution NXC. You put me on the right track to solve the problem using a recursive CTE.

    WITH 
      TablesCTE(TableName, TableID, Ordinal) AS
      (
      SELECT 
        OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,
        so.id AS TableID,
        0 AS Ordinal
      FROM dbo.sysobjects so INNER JOIN sys.all_columns ac ON so.ID = ac.object_id
      WHERE
        so.type = 'U'
      AND
        ac.is_rowguidcol = 1
      UNION ALL
      SELECT 
        OBJECT_SCHEMA_NAME(so.id) +'.'+ OBJECT_NAME(so.id) AS TableName,
        so.id AS TableID,
        tt.Ordinal + 1 AS Ordinal
      FROM 
        dbo.sysobjects so 
        INNER JOIN sys.all_columns ac ON so.ID = ac.object_id
        INNER JOIN sys.foreign_keys f 
          ON (f.parent_object_id = so.id AND f.parent_object_id != f.referenced_object_id)
        INNER JOIN TablesCTE tt ON f.referenced_object_id = tt.TableID
      WHERE
        so.type = 'U'
      AND
        ac.is_rowguidcol = 1
    )  
    SELECT DISTINCT 
      t.Ordinal,
      t.TableName
      FROM TablesCTE t
      INNER JOIN 
        (
        SELECT 
          TableName as TableName,
          Max (Ordinal) as Ordinal
        FROM TablesCTE
        GROUP BY TableName
        ) tt ON (t.TableName = tt.TableName  AND t.Ordinal = tt.Ordinal)
    ORDER BY t.Ordinal, t.TableName
    

    For thoose wondering what this is useable for: I will use it to safely empty a database without violating any foreign key relations. (By truncating in descending order) I will also be able to safely fill the tables with data from another database by filling the tables in ascending order.

提交回复
热议问题