One question came up just a day ago while I was writing SQL SERVER – 2005 – Difference Between INTERSECT and INNER JOIN – INTERSECT vs. INNER JOIN.
How many tables in database AdventureWorks have column name like ‘EmployeeID’?
It was quite an interesting question and I thought if there are scripts which can do this would be great. I quickly wrote down following script which will go return all the tables containing specific column along with their schema name.
USE AdventureWorks
GO
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%EmployeeID%'
ORDER BY schema_name, table_name;

In above query replace EmployeeID with any other column name.
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
ORDER BY schema_name, table_name;

If you want to find all the column name from your database run following script. You can down any condition in WHERE clause to get desired result.
Reference : Pinal Dave (http://blog.SQLAuthority.com)










We may also get same information through following script
——————————————————————–
USE AdventureWorks
GO
SELECT Table_Schema, Table_Name, Column_Name, Data_Type
FROM information_schema.columns
WHERE table_name in ( select name from adventureworks..sysobjects
where xtype = ‘U’ )
and column_name like ‘%EmployeeID%’
order by table_schema, table_name
——————————————————————-
Take crae
For me both solution don’t work :(
I receive this error :
Msg 195, Level 15, State 10, Line 2
‘SCHEMA_NAME’ is not a recognized function name.
I’m not DBA, than no access to the server but I can tell you it’s SQL Server 2005 ENTR + SP2 on my side I have “Microsoft SQL Server Management Studio”
Sorry, the server where I tried to execute this query is a ….. 2000 version. Thanks for your work
I am looking for a way to automatically document all the tables in my database as well as the relationships between these tables. It seems that I could start to do this via querying sys.tables and information_schema.columns, but before I started down this path, I was wondering if you could recommend a best practice for accomplishing this or recommend a software program that does this well.
Thanks in advance for your help this, and keep up the good work with the site. It is an invaluable resource for me.
David
You should make use of Generate Script option from Management studio
You can also get other objects (Tables/Views/Functions) when with the following (should work on sql2000 too):
select
o.name as tableName,
c.name as ColumnName,
o.type as ObjectType,
u.name as SchemaName
from syscolumns c
inner join sysobjects o
on o.id=c.id
inner join sysusers u
on u.uid= o.uid
where
c.name like ‘%EmployeeID%’
Thanks . It was very helpful.
thanks a lot…
select c.name, c.id, o.name from syscolums c join sysobjects o on o.id=c.id where c.name like ‘%employee%’
Hello,
I need to find the database the table and the column belong to in addition to the schema. Can someone pl. tell me how can I get this information?
Thank you,
Mahi
Hi mahi,
Chekout the column “TABLE:CATALOG” in the information_schema.tables view.
SELECT * from information_schema.tables
Hope This Helps
/Glenn
The column is TABLE_CATALOG and not TABLE:CATALOG
Sorry for the typo
/Glenn
how to find the available databse in server and how get tables and its details for each databse? Please anybody have any idea???
Thanks in advance
Mohan.V
Available databases
EXEC sp_databases
Available tables
EXEC sp_tables
select * from sysobjects where id in(select id from syscolumns where name like’empid%’)
The above query will return all columns starting with empid.
Thanks,
Pushpa
You can also use
select * from information_schema.columns
where column_name like 'empid'
how we can see specific column in sql database?
select column_name,* from information_schema.columns
where table_name = ‘Table_Name’
Can anyone tell how to find the list of tables in a database server.??
Thank u in advance……..!!!!!!!!
EXEC sp_tables
you are awesome !
Hi Suresh,
Try
select * From sys.tables
select * From sysobjects where type=’u’
Hi Pinal,
Is there a way to query an entire server to find a column from all the tables of all databases?
am creating an application where users will be searching for columns in all databases of our server. the query should return column name,data type,database name,table name.
any suggestions will be greatly appreciated..
Thanks,
Praveen
Thanks so much! That is very helpful.
Thanks a Lot…!!!!
Maby easier way with more data:
SELECT *
FROM Information_Schema.Columns
WHERE COLUMN_NAME like ‘%YOURCOLUMN%’
Yes. Also you dont need to query on system tables directly
I want to update the same column from multiple tables in database in sql server 2005.Please help in case of following query.
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE ‘%EmployeeID%’
ORDER BY schema_name, table_name;
I want to update EmployeeID from all tables which returns by above query.
You need to use dynamic SQL and table valued variable would be nice also. Consider following (sorry, didn’t have time to test this):
– Create table to hold schema and table names
DECLARE @t TABLE(Row int identity(1, 1), SchemaName nvarchar(max), TableName nvarchar(max))
– Get schema and table names from metadata
INSERT INTO @t
SELECT SCHEMA_NAME(schema_id), t.name
FROM sys.tables AS t
JOIN sys.columns c ON c.object_id = t.object_id
WHERE c.name LIKE ‘%EmployeeID%’
– These are used in iterating through the table
DECLARE @max int, @i int
SELECT @i = 1, @max = MAX(Row) IN @t
– These are used in dynamic SQL
DECLARE @sql nvarchar(max)
DECLARE @params nvarchar(max)
– @newValue is the value entered into EmployeeID
SET @params = N’@newValue int’
– Loop de loop
WHILE @i <= @max
BEGIN
– Construct dynamic SQL query
SET @sql = N'UPDATE [' +
(SELECT SchemaName FROM @t WHERE Row = @i) +
N'].[' +
(SELECT TableName FROM @t WHERE Row = @i) +
N'] SET EmployeeId = @newValue'
– Execute query
EXEC sp_executesql @sql, @params, @newValue
– Increment iterator
SET @i = @i + 1
END
thank a lot for ur help
How would you drill down to get the get the column’s value?
For instance, if I wanted to search all of the columns in a DB looking for the term ‘%Smith%’, how do I reference the columns?
thanks!!!
Hi Pinal,
I am using database DB1 and want to find all columns of a table of another database DB2.
I am trying to do this by Stored procedure but not getting any solutions. Kindly Help me out.
Thanks,
Mukesh
select * from DB2.information_schema.columns
where table_name=’some table’
Thanks for a script…..
Its very Nice…
Hi,
How to find a particular record from database tables?
Thanks in advance..
Select columns from table
where col=’some value’
Hi Madhivnan,
Thanks for ur answer….but i didnot ask for column….i need a particular record in a table….even i dont know the name of that table….for example: in employee table there is emp Column…in emp table there is a record name ‘RAJ’ …now i need to get ‘RAJ’ …i dont know employee table and emp column ..but i need record ‘RAJ’
Thank You.
Ok. Refer this post. It exactly does what you need. It searches for a particular value in all the tables and list out the table and column names if searched data are found
http://beyondrelational.com/blogs/madhivanan/archive/2009/12/14/search-a-value-in-character-column-of-all-tables.aspx
Getting an error
Help me please..
SQLSTATE = S0002
[Sybase] [ODBC Driver][Adaptive Server Anywhere]
Table ‘tables’ not found
Continue ?
Thanks
Hiii,,,
I found the solution for my above said issue.
For Sybase ASA
SELECT table_name
FROM sys.systable, sys.syscolumn
WHERE sys.systable.table_id = sys.syscolumn.table_id AND sys.syscolumn.column_name = ‘COLUMN_NAME’
ORDER BY table_name ASC;
Thanks
Hi,
I want to find all the tables in the adventureworks where the column employee id having the value ’123′ exists…
basically i want all the tables in a database where a particular column with a particular value exist.
Refer this post. This exactly does what you want to acheive
http://beyondrelational.com/blogs/madhivanan/archive/2009/12/14/search-a-value-in-character-column-of-all-tables.aspx
Hi,
I want to retrieve the row counts of all the tables present in a database using a query. Please help me.
Example
if there are 2 tables in a database called A and B having 15 and 20 results respectively. I want a query that gives
this display
TableName RowCount
A 15
B 20
it shoudl extract the names and row count itself from sys.tables.
hope m clear.
Regards,
Yogesh
Refer this
http://beyondrelational.com/blogs/madhivanan/archive/2007/11/02/different-ways-to-count-rows-from-a-table.aspx
Hi Atif Shehzad
that is good but performance point of view pinaldave
is good
all of these queries throw following error for me:
Category Timestamp Duration Message Line Position
Error 10/25/2010 1:03:34 PM 0:00:00.000 SQL Server Database Error: Incorrect syntax near ‘‘’. 58 0
line 58 is : where c.name like ‘%EmployeeID%’
not sure what’s wrong here :S …. can anyone help???
Thanks!
Can you post the exact code you used? Make sure to note that these codes will not work in versions below 2005
ok, i got this query working but it only lists column names from the dbo schema. i know i have at least one more schema in the database but its not showing any of the fields/tables from that schema.
select o.name as tableName, c.name as ColumnName, o.type as ObjectType, u.name as SchemaName
from syscolumns c inner join sysobjects o on o.id=c.id
inner join sysusers u on u.uid= o.uid
any ideas?
Thanks!
Thanks!
Our database queries solve my problem.
Thanks for the script. It worked very well.
This DOES NOT WORK.
“FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID”
Those 2 object_id values have no relationship to one another…
No. They are related
Very sorry. I was getting confused somehow by trying to query all foreign key constraints along with their table/column names. Here’s the query in case somebody else stumbles across this:
select
object_name(fk.constraint_object_id) ‘ConstraintName’,
t.name ‘TableName’,
c.name ‘ColumnName’
from sys.foreign_key_columns fk
inner join sys.tables t on fk.parent_object_id = t.object_id
inner join sys.columns c on t.object_id = c.object_id
and fk.parent_column_id = c.column_id
order by ConstraintName
Below Query also works……..
select * from information_schema.Columns where column_name Like ‘%Column_Name%’
hi,
i have multiple databases with the names:
TOY_1 (contains approx 120 tables)
TOY_2 (contains approx 150 tables)
TOY_3 (contains approx 100 tables)
….
on SQL srever 2005.
My question is: Is there a way that i can search by column name across all these databases. For eg:- if there is a column called purchase_id in table XXX of DB TOY_2, but without being aware that in which DB does this coulmn lie, can i fire a query which will search all the tables in all the DBs ( TOY_1, TOY_2,…..) and bring me back the details as to in which Db’s, which table does the column lie?
I know how to search column name when searching a single database, but i don’t know how to search across all the databases?
thanks
aseem
kindly anyone could share MCTS 70-564 dumps??
Thanks it’s useful to me
I have seen SEVERAL of your examples over the years and it is an understatement to say THANK YOU VERY MUCH. You have been very helpful and please keep up the good work.
there are > 200 DB in one instance. I want to find out with one query, dbname,schemaname,tablename,column names, column type. Could not which system tables have the relationships
Your help is appreciated,(my mail id: emailid removed)
Thanks
thanks for the info. This saved me a lot of time trying to find a known column in a large set of tables.
Hi,
Need help to fetch records. I have a table product having 2 field product_id and features. I have 5 following row
1 Camera
1 Bluetooth
1 MP3
2 Camera
3 Camera
3 MP3
Now I just want to fetch thoes products, having Camera,Bluetooth and MP3
Please suggest me to build a query
Thanks
Sheetal
select product_id from table
where product_name in (‘Camera’,'Bluetooth’,'MP3′)
group by product_id
having count(distinct product_name)=3
Hi Madhivanan,
Thanks very much for your quick response. Best part is I have tried the query as you suggested and its working. Really thanks for your help.
Sheetal
hi ,
for eg.
create view abc as
SELECT
a.pen,
b.book
from account a, books b
now i want to know the name of all those views who have books in their FROM clause. Plz suggest me to build the query.
Thanks in Advance
Hello my dear friends
I have simple code that is to get a data from couple of tables. But it showing the Result multiple times.Can any body help me.
THIS IS THE CODE.
———————————————————-
SELECT H1.EMP_CODE,H1.NAME1A+’ ‘+H1.NAME2A+’ ‘+H1.NAME3A ‘NAME’
,H2.DESCA ‘JOB’
,H3.DESCA ‘COUNTRY’
FROM H_EMP H1 INNER JOIN H_D_JOB H2
ON H1.JOB_CODE=H2.CODE
INNER JOIN H_D_NATIONALITY H3
ON H1.NAT_CODE=H3.CODE
WHERE EMP_CODE=7515
——————————————————
OUT PUT
——————————————————–
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
7515 شيخ فياز باشا مبرمج هندي
I’m really Thanks alot to help me.
I have used TM Field Finder for a while and it’s really helpfull when you need to search in SQL Server database for particular text.
CREATE VIEW [Sales].[vSalesPerson]
AS
SELECT
s.[SalesPersonID]
,c.[Title]
,c.[FirstName]
,c.[MiddleName]
,c.[LastName]
,c.[Suffix]
,[JobTitle] = e.[Title]
,c.[Phone]
,c.[EmailAddress]
,c.[EmailPromotion]
,a.[AddressLine1]
,a.[AddressLine2]
,a.[City]
,[StateProvinceName] = sp.[Name]
,a.[PostalCode]
,[CountryRegionName] = cr.[Name]
,[TerritoryName] = st.[Name]
,[TerritoryGroup] = st.[Group]
,s.[SalesQuota]
,s.[SalesYTD]
,s.[SalesLastYear]
FROM [Sales].[SalesPerson] s
INNER JOIN [HumanResources].[Employee] e
ON e.[EmployeeID] = s.[SalesPersonID]
LEFT OUTER JOIN [Sales].[SalesTerritory] st
ON st.[TerritoryID] = s.[TerritoryID]
INNER JOIN [Person].[Contact] c
ON c.[ContactID] = e.[ContactID]
INNER JOIN [HumanResources].[EmployeeAddress] ea
ON e.[EmployeeID] = ea.[EmployeeID]
INNER JOIN [Person].[Address] a
ON ea.[AddressID] = a.[AddressID]
INNER JOIN [Person].[StateProvince] sp
ON sp.[StateProvinceID] = a.[StateProvinceID]
INNER JOIN [Person].[CountryRegion] cr
ON cr.[CountryRegionCode] = sp.[CountryRegionCode];
Query is : How could we say that the above VIEW follows which type of JOIN by looking at resultset or View ?
Is there any query to find all the references of a particular column in a table? In other way how to find where and all that particular column (not the name, actual column refernce) is used? (ex: sps, user function, FK , views etc)
Query on definition colum of the system table sys.sql_modules
Hi,
I want to retrieve some of cloumn names form table..is that possible ?
Thanks
Venkat
Select column_name from information_schema.columns where table_name=’table name’
if you have a ntext column is does not work….
Example :
if i want to search for any columns that contain value:%SKUS% it doesn’t show anything…
Hi friends
I know only DBMS concepts
give me tips to know SQL
hi friends
i need your help to study SQL
I’m not a big commenter, but I just wanted to say thanks. I end up finding answers on your blog really often, and I really should take the time to say thank you.
Soo…thanks for being so concise, and for taking the time to share your knowledge, it is much appreciated.
This script is awesome. Thanks for sharing with the community. I finished my work alot faster now.
Hi Guys,
I often come across the situation where i need to find the column name having particular value of unknown table in a Sql database. For example, I know the value of a column like ‘Test’ and i need to find the Column name and table name in the particular data base. Please share if i can query like that.
Thanks and Regards,
Parthiban Sekar
You saved me more than million times. Thank YOU!
HI,
I need query which will find common tables from different databases..?
Example code
exec sp_msforeachdb ‘if exists(select * from ?..sysobjects where name=”TABLE_PRIVILEGES”) select ”TABLE_PRIVILEGES”’