quarta-feira, 5 de novembro de 2014

Listing all columns that should be a FK ...but are not defined as a FK

I had to list alll columns that should set as FK ... but for some odd reason are not.

SELECT Schema_name(schema_id) + '.' + t.NAME, 
       c.NAME 
FROM   sys.columns c 
       JOIN sys.tables t 
         ON ( c.object_id = t.object_id ) 
--columns not set as a FK 
WHERE  c.NAME NOT IN (SELECT c.NAME AS ForeignKeyColumn 
                      FROM   sys.foreign_key_columns AS fk 
                             INNER JOIN sys.tables AS t 
                                     ON fk.parent_object_id = t.object_id 
                             INNER JOIN sys.columns AS c 
                                     ON fk.parent_object_id = c.object_id 
                                        AND fk.parent_column_id = c.column_id) 
       --BUT THEY HAVE A CORRESPONDING pk COLUMN SOMEWHERE 
       AND c.NAME IN (SELECT ColumnName = col.NAME 
                      FROM   sys.indexes ind 
                             INNER JOIN sys.index_columns ic 
                                     ON ind.object_id = ic.object_id 
                                        AND ind.index_id = ic.index_id 
                             INNER JOIN sys.columns col 
                                     ON ic.object_id = col.object_id 
                                        AND ic.column_id = col.column_id 
                             INNER JOIN sys.tables t 
                                     ON ind.object_id = t.object_id 
                             INNER JOIN sys.schemas sc 
                                     ON SC.schema_id = T.schema_id 
                      WHERE  ind.is_primary_key = 1) 
       --but they are not THAT pk column ... =) 
       AND C.column_id NOT IN (SELECT col.column_id 
                               FROM   sys.indexes ind 
                                      INNER JOIN sys.index_columns ic 
                                              ON ind.object_id = ic.object_id 
                                                 AND ind.index_id = ic.index_id 
                                      INNER JOIN sys.columns col 
                                              ON ic.object_id = col.object_id 
                                                 AND ic.column_id = 
                                                     col.column_id 
                                      INNER JOIN sys.tables t 
                                              ON ind.object_id = t.object_id 
                                      INNER JOIN sys.schemas sc 
                                              ON SC.schema_id = T.schema_id 
                               WHERE  ind.is_primary_key = 1) 

Check out my new book on MariaDB http://www.amazon.com/dp/B00MQC06HC

Nenhum comentário:

Postar um comentário

Leave your comment here!