Search Particular Column in all Tables or Views in Sql Server Database

Introduction: In this article I have explained How to find all tables or views in sql server database that contain a specific column. Or we can say list out all the table and views where particular column exists.

In previous articles i explained the Query to get age in years, months and days from date of birth and Query to get upcoming birthdays within week and Without primary key column update first or last n records in table and Insert into select from statement to copy data from one table to another and Query to count male, female and total employees

Description: While working with sql server database it may be required to search for a specific column in all the tables for many reasons e.g. to change that column name or its data type or length etc.I have mentioned the query to frequently list out all the table and views where the column exists that we want to search.

Implementation: Let’s write the queries to list tables containing desired column. 

Query to Search column in all table

DECLARE @ColumnName NVARCHAR(50)= 'BookPrice'

SELECT
scm.name AS 'Schema',
tbl.name   AS 'Table',
clm.name AS 'Column'
FROM sys.columns clm
INNER JOIN sys.tables tbl ON tbl.object_id = clm.object_id
INNER JOIN sys.schemas scm ON tbl.schema_Id = scm.Schema_Id
WHERE clm.name LIKE '%' + @ColumnName + '%'
ORDER BY scm.name, tbl.name, clm.name

Result: 
Schema
Table
Column
dbo
tbBookDetails
BookPrice
dbo
tbBookMaster
BookPrice
dbo
tbBooks
BookPrice

Query to Search column in all table and Views

DECLARE @ColumnName NVARCHAR(50)= 'BookPrice'

SELECT
TABLE_SCHEMA   AS 'Schema',
TABLE_NAME       AS 'Table/View',
COLUMN_NAME  AS 'Column'
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
COLUMN_NAME LIKE '%' + @ColumnName + '%'
ORDER BY COLUMN_NAME

Result 
Schema
Table/View
Column
dbo
tbBooks
BookPrice
dbo
tbBookMaster
BookPrice
dbo
vwBookDetails
BookPrice
dbo
tbBookDetails
BookPrice

 Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

1 comments:

Click here for comments
August 18, 2016 ×

Thanks pritesh for your comment..Stay connected and keep reading

Congrats bro Lalit Raghuvanshi you got PERTAMAX...! hehehehe...
Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..