Monday 2 July 2018

Get All Primary Key In SQL

-- Let's get the columns of the Primary key into a CTE 
;WITH mycte 
     AS (SELECT Schema_name(o.schema_id)            AS 'Schema', 
                Object_name(i2.object_id)           AS 'TableName', 
                Stuff((SELECT ',' + Col_name(ic.object_id, ic.column_id) 
                       FROM   sys.indexes i1 
                              INNER JOIN sys.index_columns ic 
                                      ON i1.object_id = ic.object_id 
                                         AND i1.index_id = ic.index_id 
                       WHERE  i1.is_primary_key = 1 
                              AND i1.object_id = i2.object_id 
                              AND i1.index_id = i2.index_id 
                       FOR xml path('')), 1, 1, '') AS PK 
         FROM   sys.indexes i2 
                INNER JOIN sys.objects o 
                        ON i2.object_id = o.object_id 
         WHERE  i2.is_primary_key = 1 
                AND o.type_desc = 'USER_TABLE') 

-- Use this select to get the count, join to the CTE and get the column list 

SELECT Schema_name(o.schema_id)                    AS 'Schema', 
       Object_name(i.object_id)                    AS 'TableName', 
       Count(Col_name(ic.object_id, ic.column_id)) AS 'Primary_Key_Column_Count' 
       , 
       mycte.pk                                    AS 
       'Primary_Key_Columns' 
FROM   sys.indexes i 
       INNER JOIN sys.index_columns ic 
               ON i.object_id = ic.object_id 
                  AND i.index_id = ic.index_id 
       INNER JOIN sys.objects o 
               ON i.object_id = o.object_id 
       INNER JOIN mycte 
               ON mycte.tablename = Object_name(i.object_id) 
WHERE  i.is_primary_key = 1 
       AND o.type_desc = 'USER_TABLE' 
GROUP  BY Schema_name(o.schema_id), 
          Object_name(i.object_id), 
          mycte.pk   
ORDER  BY 'TableName' ASC   

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...