Vinyl Windows
Vinyl Windows

Reputation: 503

How to query for columns in sql database

I am merging a few tables and I need to query for specific column names. Reason being these tables I am condensing have FK candidate columns but no FK so I would have to keep looking through every table to see if it contained a specific column name and that seems to be wearing on the eyes a little.

I got this from another post but it is not complete.

SELECT 'SELECT ''' + TABLE_NAME + '.' + column_name + 
   ''' FROM ' + TABLE_NAME + ' WHERE ' + 
   column_name + ' = ''[THE COLUMN NAME I AM LOOKING FOR]'''
FROM INFORMATION_SCHEMA.COLUMNS 

The TSQL above seems to not be structured correctly or I am missing something.

Upvotes: 1

Views: 162

Answers (1)

Yuck
Yuck

Reputation: 50855

This query will get a list of columns (along with their schema and table names) matching whatever you put into the parameter @SomeColumnName:

DECLARE @SomeColumnName VarChar(200) = 'Test';

SELECT S.name SchemaName, T.name TableName, C.name ColumnName
FROM sys.columns C
     JOIN sys.tables T ON C.object_id = T.object_id
     JOIN sys.schemas S ON T.schema_id = S.schema_id
WHERE C.name = @SomeColumnName;

And if you are using a version of SQL Server that doesn't have the newer DMVs, use this:

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = @SomeColumnName;

Upvotes: 2

Related Questions