When developing queries in SQL Server, you might have come across the need to list all the tables that have a specific column name. Sure, you can write a query using
sysobjects etc., but you will have to write it every time or save it somewhere - I am too lazy for that. In this article, we'll create a Stored Procedure that will work as easy as
sp_help, only for columns!
To give a better idea, below is the query that we would normally use to search for a column name:
SELECT sysobjects.name as "Table",
syscolumns.name as "Column"
from sysobjects , syscolumns
where sysobjects.id = syscolumns.id
and sysobjects.xtype = 'u'
and syscolumns.name like '%order%'
order by sysobjects.name, syscolumns.name
This will return all tables where the column name contains the text 'order'. As the results are what we're looking for, we'll use this query as the basis for our solution.
Using the code
As I have mentioned earlier, we are looking for a solution similar to
sp_help; therefore, we'll create a Stored Procedure on the Master database of the SQL Server instance.
The code and principle are simple, but works really cool. First, we need the database of the active query window:
SET @DataBase = (SELECT DB_NAME())
Now, we build some dynamic SQL with the database name of our active query window (same query as above) and execute it.
SET @SQL = 'SELECT a.name AS [Table],'
SET @SQL = @SQL + ' b.name as [Column]'
SET @SQL = @SQL + ' from ' + @DataBase + '..sysobjects a , '
SET @SQL = @SQL + @DataBase + '..syscolumns b'
SET @SQL = @SQL + ' where a.id = b.id'
SET @SQL = @SQL + ' and a.xtype = ''u'''
SET @SQL = @SQL + ' and b.name like ''' + '%' + @ColumnName + '%''' + ''
SET @SQL = @SQL + ' order by a.name, b.name'
Voila, once we have created the Stored Procedure, we will be able to search for column names from the active query window in the following way:
which will give us the following results when using the Northwind database:
But wait, there's more
We can configure a keyboard shortcut for this in SQL Server Management Studio:
From the Tools menu, select Options. From the left hand pane under Environment, select Keyboard. In one of the available Query shortcuts, enter
Now we can easily highlight the name of the column we're searching for, e.g.,
order and hit Ctrl + 3.
Points of interest
While I was doing this, I also came across
syscomments, which enables us to search for phrases in Stored Procedures and functions. That's a short and sweet principle, and I will post that to the Tips and Tricks section of The Code Project. Enjoy!