Tuesday, January 10, 2012

SQL: Hints: Find all tables that contain a given column

This falls under the category of SQL Hints. These are things I need to do occassionally, and normallly forget the exact sytax required, so I will place it here in case I need it in the future.

If you have a large database with many tables, you sometimes may need to quickly find out all the tables that contain a certain column.  The below query will list out all the tables that contain the given column name (in this example 'user_name'). 

DECLARE @String varchar(100)
SET @String = 'user_name'
SELECT
DISTINCT
o.name as Table_Name, c.name as Column_Name, c.is_nullable
FROM sys.columns c
INNER JOIN sys.objects o
ON c.object_id = o.object_id
WHERE c.name = @String
ORDER BY o.name

Output will be like this:
Table_NameColumn_Nameis_nullable
usersuser_name0
ordersuser_name1
logsuser_name1

1 comment:

macareopaetzold said...

Harrah's Cherokee Casinos announce opening date for
Harrah's Cherokee 김제 출장안마 Casinos announced Thursday they 문경 출장안마 have begun 성남 출장샵 accepting COVID-19 cases. Harrah's Cherokee Casinos 서귀포 출장샵 will operate 정읍 출장샵 in