Search a column name across all databases

SyntaxError picture SyntaxError · Aug 21, 2012 · Viewed 13.8k times · Source

I have this query that finds all tables and views that matches my column name of a certain database. I am using SQL SERVER 2008

SELECT table_name FROM information_schema.columns
WHERE column_name = 'product_name'

I want to extend the capability of my query to search across all databases and even look for Stored procedures whose having my searched column name.

Answer

Shiva picture Shiva · Apr 11, 2014

This script will search your column in all tables across all databases.

Create table #yourcolumndetails(DBaseName varchar(100), TableSchema varchar(50), TableName varchar(100),ColumnName varchar(100), DataType varchar(100), CharMaxLength varchar(100))

EXEC sp_MSForEachDB @command1='USE [?];
    INSERT INTO #yourcolumndetails SELECT
    Table_Catalog
    ,Table_Schema
    ,Table_Name
    ,Column_Name
    ,Data_Type
    ,Character_Maximum_Length
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME like ''%yourcolumnname%'''

select * from #yourcolumndetails
Drop table #yourcolumndetails