Find Tables Where a Column is Used in Primary Key Definition
On SQL Server, to find the list of database tables where a specific column based on column name is used in primary key definitions, T-SQL developers can use the SQL Select script which I shared in this tutorial.
For example, if you are looking for all tables where ProductID column is used in the primary key definitions of a database table in SQL Server sample database AdventureWorks, you might be expecting to get a list of database tables:
Product, ProductDocument, ProductInventory, ProductVendor, WorkOrderRouting, etc.
All these tables have a primary key defined and in that primary key (it might be a composite key) the ProductId column name is used as a part of the key.
Let's first execute following SQL SELECT statement which returns the list of table names on a SQL Server database for a given column filtered in all table primary key index list.
Database developers can see in the output of the above SQL script that all tables are listed with their primary index names for filtered table field name in WHERE clause
If you check the SQL code, database developers will realize that the main solution for this task comes from usage of system views like sysobjects, sysindexes, SysIndexKeys and syscolumns.
SQL programmers can also convert the above SELECT command into a user-defined table-valued SQL function, if it will be used frequently
Then the table-value SQL function can be executed as seen in below sample code
The output of the above SQL function code will be same with first code sample