views:

1157

answers:

5

I am working on a SQL Server 2008 Db that has many tables in it (around 200). Many of these tables contain a field by the name "CreatedDate". I am trying to identify all the table schema with this particular field.

Is there a SQL query to do this?

Appreciate your response!

+2  A: 
  select object_name(c.object_id) as table_name
    , schema_name(t.schema_id) as schema_name
    from sys.columns c
    join sys.tables t on c.object_id = t.object_id
     where c.name=N'CreatedDate';

It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.

Remus Rusanu
i got the error 'Invalid column name 'schema_id'
pencilslate
This worked!select object_name(sc.object_id) as table_name, schema_name(st.schema_id) as schema_name from sys.columns sc, sys.tables st where sc.name=N'CreatedDate';
pencilslate
wrigth, I was writing the query from memory, forgot sys.columns doesn't store the schema.
Remus Rusanu
I prefer this one. Information_schema can get out of synch with the database, but this query can't.
jcollum
A: 

Same thing but in ANSI way

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'CreateDate' )

Tamil.SQL
+2  A: 

I would query the information_schema - this has views that are much more readable than the underlying tables.

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%create%'
Raj More
It worked! Better version too.
pencilslate
A: 

My favorite...

SELECT objParent.name AS parent, obj.name, col.*
FROM sysobjects obj 
    LEFT JOIN syscolumns col
        ON obj.id = col.id
    LEFT JOIN sysobjects objParent
        ON objParent.id = obj.parent_obj
WHERE col.name LIKE '%Comment%'
   OR obj.name LIKE '%Comment%'

Above I'm searching for "Comment".

Drop the percent signs if you want a direct match.

This searches tables, fields and things like primary key names, constraints, views, etc.

And when you want to search in StoredProcs after monkeying with the tables (and need to make the procs match), use the following...

SELECT name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%Comment%'

Hope that helps, I find these two queries to be extremely useful.

Allbite
A: 

You do not need to type SQL Query for this in SQL Server 2008.

In SSMS Object Explorer choose Databases or Tables of the required database (if you need to search in one database), open menu View--> Object Explorer Details (alternatively press F7), type %CreatedDate% in Search textbox, ENTER, enjoy

vgv8