I needed to search a column by name FileID across all databases. I found many blogs to search the column in a single database. I explored many ways and finally I was able to develop this script successfully. The below script searches the specified column in all tables(tables and views only) across all databases.
Search columns Within the database
If you know database name and want to know the table name where your column exists, you can execute this script.The below script searches column in all tables and views.
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 ''%FileID %'''
select * from #yourcolumndetails
Drop table #yourcolumndetails
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 ''%FileID %'''
select * from #yourcolumndetails
Drop table #yourcolumndetails
Search columns Within the database
If you know database name and want to know the table name where your column exists, you can execute this script.The below script searches column in all tables and views.
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%FileID%'
FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%FileID%'
No comments:
Post a Comment