SQL Server – How to Select Column Names by Data Type

sql server

How would I get the names of all the columns in a table that are of a specific type such as datetime?

Even better — How can I do the same thing but with multiple tables joined together and then list the column name along with the table it comes from?

Best Answer

How would I get the names of all the columns in a table that are of a specific type such as datetime?

(output as schema_name | table_name | column_name | data_type):

SELECT Object_Schema_name(c.object_id) as [SCHEMA_NAME]
    ,object_NAME(c.object_id) AS TABLE_NAME
    ,c.NAME AS COLUMN_NAME
    ,t.NAME AS DATA_TYPE
    -- add / remove columns as per need
    --,c.max_length AS MAX_LENGTH
FROM sys.all_columns c
INNER JOIN sys.types t ON t.system_type_id = c.system_type_id
where Object_Schema_name(c.object_id) <> 'sys' -- not sys schema
    -- filters 
        and t.name = 'Datetime'
    --  and object_NAME(c.object_id) = 'someTableName'