In [SQL Server Management Studio] ([SSMS]), we can use a script to obtain all tables' primary keys. This will come in handy if you have many tables and need to find relationships between them using their [Primary Key].
In SSMS, open a New Query editor.
Copy and paste this code into the editor.
Next, press [Execute] or [F5] to run the script.
CFFCS | CarrzSynEdit: | SQL Script

SELECT 
    s.name AS SchemaName,
    t.name AS TableName,
    i.name AS PKName,
    c.name AS ColumnName
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.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
INNER JOIN sys.tables t ON i.object_id = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE i.is_primary_key = 1
ORDER BY SchemaName, TableName, ic.key_ordinal;

The outcome will give results similar to this, using our Virtual Class Database.
dboAvailabilityPK_AvailabilityUNID
dboCityPK_CityCityID
dboCookieDemoPK_CookieDemoID
dboCountryPK_CountryCountryID
dboDropDownPK_DropDownddID
dboDropdown2PK_Dropdown2InsertID
dboImageServerPK_ImageServerPicsID
dboImageUploadPK_ImageUploadPicsID
dboISTagPK_ISTagISKID
dboISTagsPK_ISTagsISKsID
dboLoadItPK_LoadItID
dboMTimePK_MTimeID
dboNamesPK_NamesID
dboNamesListPK_NamesListID
dboPagingPK_PagingID
dboPopulationPK_PopulationPopulationID
dboStatePK_StateStateID
dboTagsPK_TagsTagID
dboTeachingPK_TeachingID
dboTestTablePK_TestTableTestID
dboXMLSitemapPK_XMLXMLID
dboZipTablePK_ZipTableZipID
Once you have this information, you might want to check each Primary Key to see which tables it is used as a Foreign Key in. Use the article below to learn more.▼
Other Articles Related to this Entry.