/ Published in: SQL
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
--Create temp tables to store sys data CREATE TABLE #DBList(id INT IDENTITY (1,1), DBName nvarchar(50)) CREATE TABLE #TableList(id INT IDENTITY (1,1), DBName nvarchar(50), TableName Nvarchar(200), columnName nvarchar(200)) CREATE TABLE #ColumnList(id INT IDENTITY (1,1), DBName nvarchar(50), TableName Nvarchar(200), tbi INT,columnName nvarchar(200)) --get a list of non system DBs INSERT INTO #DBList(DBName) SELECT name FROM master..sysDatabases WHERE sid !=0x01 --declare variables DECLARE @i INT DECLARE @max1 INT DECLARE @db nvarchar(50) DECLARE @SQL nvarchar(4000) DECLARE @sql1 nvarchar(4000) DECLARE @tbi INT DECLARE @colID INT DECLARE @MAX INT DECLARE @dbname nvarchar(400) DECLARE @tbid INT DECLARE @tbl nvarchar(50) DECLARE @svr AS nvarchar(50) --set initial state of variables SET @i=1                                                                 --counter SET @max1 =(SELECT MAX(id) FROM #DBList)+1         --maximum value to iterate to SET @svr= UPPER(@@servername)                            --name of server SET @colID=1                                                         ---gets a list of databases from server and populate #DBList table         while @i <@max1                 BEGIN                     SET @db = (SELECT DBname FROM #DBList WHERE @i=id)                     SET @SQL ='select '''+@db+''' ,id,name from '+ @db+'..sysobjects                                                                                 where xtype =''u'''                     SET @i=@i+1                     INSERT INTO #ColumnList(DbName,tbi, TableName)                     EXEC (@SQL) END --get details based on column id     SET @MAX=(SELECT MAX(id) FROM #ColumnList)+1         while @colID < @MAX             BEGIN                 SET @dbname=(SELECT dbname FROM #ColumnList WHERE id=+ @colID)                 SET @tbid=(SELECT tbi FROM #ColumnList WHERE id=+ @colID)                 SET @tbl=(SELECT tablename FROM #ColumnList WHERE id=+ @colID)                 SET @sql1='select '''+@dbname +''','''+@tbl+''' ,name from ['+@dbname +']..syscolumns                 where id='+ CAST(@tbid AS nvarchar(20))                 INSERT INTO #TableList(dbname,Tablename,columnName)                 EXEC(@sql1)                 SET @colID=@colID+1 END --Select from Temp Table SELECT @svr AS Svr,DBName,TableName,ColumnName FROM #TableList ORDER BY DBname,tablename, columnname --CleanUp DROP TABLE #DBList DROP TABLE #TableList DROP TABLE #ColumnList