Wednesday, April 23, 2025

SQL Server - Get all Tables and Columns from ALL Databases

 This query below gives you All Tables with Columns in All the database in SQL Server:

SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, TableName sysname,
ColumnID sysname, ColumnName sysname, ColumnType sysname, IsNullable sysname)
DECLARE
@SearchDb nvarchar(200)
,@SearchSchema nvarchar(200)
,@SearchTable nvarchar(200)
,@SQL nvarchar(4000)
SET @SearchDb='%'
SET @SearchSchema='%'
SET @SearchTable='%'
SET @SQL='select ''?'' as DbName, s.name as SchemaName, t.name as TableName,
c.column_id, c.name ColumnName, tp.name ColumnType, c.is_nullable
from [?].sys.tables t
inner join [?].sys.schemas s
on t.schema_id=s.schema_id
inner join [?].sys.columns c
on t.object_id = c.object_id
inner join [?].sys.types tp
on c.system_type_id = tp.system_type_id
where ''?'' like '''+@SearchDb+'''
and s.name like '''+@SearchSchema+'''
and t.name like '''+@SearchTable+''''

INSERT INTO @AllTables (DbName, SchemaName, TableName, ColumnID, ColumnName, ColumnType, IsNullable)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
--SELECT DbName, SchemaName, count(1) FROM @AllTables
select DbName, SchemaName, TableName, ColumnName, ColumnType,
case when IsNullable = 0 then 'Not Null' else '' end "IsNullable"
from @AllTables
where DbName in ('list of dbs interested in or comment out this filter')
--group by DbName, SchemaName
ORDER BY DbName, SchemaName, TableName, ColumnID;