Wednesday, March 28, 2012

Return all PKs in DB all tables

I'm trying to get all the PKs for all the tables in a DB. Right now I'm usi
ng:
sp_msforeachtable "print '?' exec sp_pkeys @.table_name = '?'"
However sp_msforeachtable returns the table names as [dbo].[tablename]. The
sp_pkeys proc takes tablename without dbo. or the brackets '[].'
Is there a better way to do this or what should I do to modify the script?
-PeterHi,
From the sysobjects tables you get the name of all primary keys. In the
criteria you can mention xtype = 'PK'
Select Name from sysobjects Where Xtype = 'PK'
For getting all the columns associated the primary key you could join
SYSOBJECTS table with INFORMATION_SCHEMA.KEY_COLUMN_USAGE
view
Thanks
Hari
SQL Server MVP
"Peter L." <PeterL@.discussions.microsoft.com> wrote in message
news:04CD0D49-5925-4EB2-9D1B-5CCE728A5E75@.microsoft.com...
> I'm trying to get all the PKs for all the tables in a DB. Right now I'm
> using:
> sp_msforeachtable "print '?' exec sp_pkeys @.table_name = '?'"
> However sp_msforeachtable returns the table names as [dbo].[tablename].
> The
> sp_pkeys proc takes tablename without dbo. or the brackets '[].'
> Is there a better way to do this or what should I do to modify the script?
> --
> -Peter

No comments:

Post a Comment