How To List Database/Table/Primary Key using T-SQL in SQL Server 2012

How do I use T-SQL in a query to list every Database, Table, and the table's Primary Key in an SQL Server 2012 environment?
LVL 16
Chuck WoodAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
EXECUTE master.dbo.sp_msforeachdb
      'USE [?];
      SELECT O.name AS TableName,
            I.name AS PrimaryKeyName
      FROM sys.objects AS O
      INNER JOIN sys.indexes AS I
            ON O.object_id = I.object_id
            AND I.is_primary_key = 1
      WHERE O.[type] = ''U'''
0
Chuck WoodAuthor Commented:
Brian-
That looks good but  I also need the database name.
0
Brian CroweDatabase AdministratorCommented:
EXECUTE master.dbo.sp_msforeachdb
      'USE [?];
      SELECT ''?'' AS DatabaseName, O.name AS TableName,
            I.name AS PrimaryKeyName
      FROM sys.objects AS O
      INNER JOIN sys.indexes AS I
            ON O.object_id = I.object_id
            AND I.is_primary_key = 1
      WHERE O.[type] = ''U'''
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Brian CroweDatabase AdministratorCommented:
If you want them all in the same resultset then you can have them insert into a temp table instead of just doing a select
0
Chuck WoodAuthor Commented:
Brian-
Yes, I would like to have them in the same result set.
0
Chuck WoodAuthor Commented:
And I see I was not clear enough. I need to have the name of the  column which is the primary key instead of the name of the primary key itself.
0
Brian CroweDatabase AdministratorCommented:
try this...I chose to display the column name as a comma-delimited list in the case that there are multiple columns in the PK

EXECUTE master.dbo.sp_msforeachdb
	'USE [?];
	SELECT ''?'' AS DatabaseName, T.name AS TableName,
		I.name AS PrimaryKeyName,
		STUFF(
		(
			SELECT '','' + C.name
			FROM sys.index_columns AS IC
			INNER JOIN sys.columns AS C
				ON IC.[object_id] = C.[object_id]
				AND IC.column_id = C.column_id
			WHERE IC.[object_id] = I.[object_id]
				AND IC.index_id = I.index_id
			ORDER BY IC.key_ordinal
			FOR XML PATH('''')
		), 1, 1, '''') AS PrimaryColumnList
	FROM sys.tables AS T
	INNER JOIN sys.indexes AS I
		ON T.[object_id] = I.[object_id]
		AND I.is_primary_key = 1
	WHERE T.[type] = ''U''
	ORDER BY T.name'

Open in new window

0
Brian CroweDatabase AdministratorCommented:
In the same resultset...

CREATE TABLE #PrimaryKey
(
	DatabaseName	VARCHAR(128),
	TableName		VARCHAR(128),
	PKColumnList	VARCHAR(MAX)
);

EXECUTE master.dbo.sp_msforeachdb
	'USE [?];
	INSERT #PrimaryKey (DatabaseName, TableName, PKColumnList)
	SELECT ''?'' AS DatabaseName, T.name AS TableName,
		STUFF(
		(
			SELECT '','' + C.name
			FROM sys.index_columns AS IC
			INNER JOIN sys.columns AS C
				ON IC.[object_id] = C.[object_id]
				AND IC.column_id = C.column_id
			WHERE IC.[object_id] = I.[object_id]
				AND IC.index_id = I.index_id
			ORDER BY IC.key_ordinal
			FOR XML PATH('''')
		), 1, 1, '''') AS PrimaryKeyColumnList
	FROM sys.tables AS T
	INNER JOIN sys.indexes AS I
		ON T.[object_id] = I.[object_id]
		AND I.is_primary_key = 1
	WHERE T.[type] = ''U''
	ORDER BY T.name'

SELECT * FROM #PrimaryKey

Open in new window

0
Chuck WoodAuthor Commented:
That is working well except I need to have just one result set. Is that possible?
0
Brian CroweDatabase AdministratorCommented:
If you want to exclude system databases...

CREATE TABLE #PrimaryKey
(
	DatabaseName	VARCHAR(128),
	TableName		VARCHAR(128),
	PKColumnList	VARCHAR(MAX)
);

EXECUTE master.dbo.sp_msforeachdb
	'USE [?];
	IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'')
	INSERT #PrimaryKey (DatabaseName, TableName, PKColumnList)
	SELECT ''?'' AS DatabaseName, T.name AS TableName,
		STUFF(
		(
			SELECT '','' + C.name
			FROM sys.index_columns AS IC
			INNER JOIN sys.columns AS C
				ON IC.[object_id] = C.[object_id]
				AND IC.column_id = C.column_id
			WHERE IC.[object_id] = I.[object_id]
				AND IC.index_id = I.index_id
			ORDER BY IC.key_ordinal
			FOR XML PATH('''')
		), 1, 1, '''') AS PrimaryKeyColumnList
	FROM sys.tables AS T
	INNER JOIN sys.indexes AS I
		ON T.[object_id] = I.[object_id]
		AND I.is_primary_key = 1
	WHERE T.[type] = ''U''
	ORDER BY T.name'

SELECT * FROM #PrimaryKey

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chuck WoodAuthor Commented:
Never mind. I missed copying part of the code. That works great.
0
Chuck WoodAuthor Commented:
Excluding system databases is a nice touch.
0
Chuck WoodAuthor Commented:
Great solution; exactly what I wanted. Thank  you Brian.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.