SQL – List Primary key and Concatenate composite Keys into a single row separed by comma

The following query lists all the Primary keys of all the table. 

OP has requested to list all PK and composite PKs and concatenate all it’s composite PK column values into a single row separated by comma hence this post.

 
SELECT TAB.TABLE_NAME,COL.COLUMN_NAME  
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS TAB,  
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE COL  
WHERE  
    COL.CONSTRAINT_NAME = TAB.CONSTRAINT_NAME 
    AND COL.TABLE_NAME = TAB.TABLE_NAME 
    AND CONSTRAINT_TYPE = 'PRIMARY KEY' 
 
 
 
 In the above screenshot  the invoices and PK_TEST table has composite PK’s. Query to get the Composite PKs in a single row separated by comma
 
SELECT TABLENAME, 
       LEFT(COL,LEN(COL)-1) AS COLUMN_NAME 
FROM 
( 
        SELECT DISTINCT TAB.TABLE_NAME TABLENAME, 
            ( 
            SELECT COL.COLUMN_NAME +','  AS [text()] 
            FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE COL  
            WHERE  
                COL.CONSTRAINT_NAME = TAB.CONSTRAINT_NAME AND COL.TABLE_NAME = TAB.TABLE_NAME AND CONSTRAINT_TYPE = 'PRIMARY KEY' 
             FOR XML PATH ('') 
            ) COL 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TAB 
 )T 
 where T.COL is NOT NULL 
 

 

 

Advertisements

About Prashanth Jayaram

I’m a Database technologist having 11+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My expertise lies in T-SQL programming, Replication and PowerShell You can connect me via https://social.technet.microsoft.com/profile/prashanth jayaram/ http://www.sqlshack.com/author/prashanth/ https://www.tumblr.com/blog/prashantjayaram http://www.sqlservercentral.com/blogs/powersql-by-prashanth-jayaram/ http://www.toadworld.com/members/prashanthjayaram/ My Articles are published in following sites http://www.ssas-info.com/analysis-services-articles/ http://db-pub.com/ http://www.sswug.org/sswugresearch/community/
This entry was posted in SQL and tagged , , , . Bookmark the permalink.

3 Responses to SQL – List Primary key and Concatenate composite Keys into a single row separed by comma

  1. dhivya sharmi says:

    its useful to us we hope it may useful for all of you

  2. Saad Husain says:

    Very useful in documenting a previously undocumented database. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s