簡體   English   中英

在 SQL Server 中查找丟失的外鍵/主鍵

[英]Find missing foreign/primary keys in SQL Server

我正在尋找一個可以列出丟失的 PK 和 FK 的查詢。

我修改了這個查詢,最后得到了這個代碼:

-- Find columns on tables with names like FooID or FooCode which should
-- be part of primary or foreign keys, but aren't.
SELECT t.name AS [Table], 
       c.name AS [Column], 
       a.total_pages / 128.00 AS Total_MB
FROM sys.tables t
     INNER JOIN sys.syscolumns c ON c.id = t.object_id               
     -- Join on foreign key columns        
     LEFT JOIN sys.foreign_key_columns fkc ON(fkc.parent_object_id = t.object_id
                                              AND c.colid = fkc.parent_column_id)
                                             OR (fkc.referenced_object_id = t.object_id
                                                 AND c.colid = fkc.referenced_column_id)                
     -- Join on primary key columns        
     LEFT JOIN sys.indexes i ON i.object_id = t.object_id
                                AND i.is_primary_key = 1
     LEFT JOIN sys.index_columns ic ON ic.object_id = t.object_id
                                       AND ic.index_id = i.index_id
                                       AND ic.column_id = c.colid
     INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID
                                    AND i.index_id = p.index_id
     INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
WHERE t.is_ms_shipped = 0
      AND (c.name LIKE '%ID'
           OR c.name LIKE '%Code')
      AND (fkc.constraint_object_id IS NULL 
           -- Not part of a foreign key                 
           AND ic.object_id IS NULL 
      -- Not part of a primary key        
      )
      AND (                
      -- Ignore some tables                
      t.name != 'sysdiagrams'
      AND t.name NOT LIKE '[_]%' 
      -- temp tables                
      AND t.name NOT LIKE '%temp%'
      AND t.name NOT LIKE '%Log%' 
      -- log tables                                
      -- Ignore some columns                
      AND c.name NOT IN('GLCode', 'EID', 'AID'))
     AND a.total_pages > 1.0
-- external keys        
ORDER BY t.name, 
         c.name;

我的問題是關於第 40 行: AND a.total_pages > 1.0

  • 如果您注釋掉該行,它將返回您所有丟失的 PK 和 FK
  • 如果您使用該行,則目標是僅返回大小 > 1MB 的表

...但相反還返回了大小為 0.085937 的表

在此處輸入圖片說明

你的情況是:

and a.total_pages > 1.0

但是您的選擇條款說:

a.total_pages / 128.00 AS Total_MB

如果要過濾大於 1 MB 的大小,則可能需要以下條件:

and a.total_pages > 128

表別名a指的是sys.allocation_units ,它位於幾個left outer joinleft outer join where子句中使用它而不允許null值將連接從left outer更改為inner 這將解釋當條件被注釋掉時返回的“丟失”關鍵行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM