I have the below script that works fine & fetches all the results I need. However It does it only for the current DB context. I have several hundred databases in my instance and need to get the results for all databases in a single execution.
How do I modify the script to make it work for all Databases.
IF OBJECT_ID('tempdb..#AllInfo', N'U') IS NOT NULL DROP TABLE #AllInfo;
CREATE TABLE #AllInfo (
dbase_name nvarchar(200),
tbl_name nvarchar(300),
column_name nvarchar(300),
min_date datetime
)
DECLARE @Statement varchar(2000);
DECLARE cr_MaxDateTime CURSOR LOCAL FOR
SELECT 'SELECT DB_NAME(), ' + '''' + TAB.name + '''' + ', ' + '''' + COL.name + '''' +' ,MIN([' + COL.name +']) AS ''Min' + COL.name + '_' + TAB.name + ''' FROM [' + SCH.name + '].[' + TAB.name + ']'
FROM sys.schemas AS SCH
INNER JOIN sys.tables AS TAB
ON TAB.schema_id = SCH.schema_id
INNER JOIN sys.columns AS COL
ON COL.object_id = TAB.object_id
INNER JOIN sys.types AS UDT
ON COL.user_type_id = UDT.user_type_id
INNER JOIN sys.types AS TYP
ON TYP.system_type_id = UDT.system_type_id AND
TYP.user_type_id = TYP.system_type_id AND
TYP.name IN ('date', 'datetime2', 'datetimeoffset', 'datetime', 'time')
ORDER BY SCH.name, TAB.name, COL.name
FOR READ ONLY;
OPEN cr_MaxDateTime;
FETCH cr_MaxDateTime INTO @Statement;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Statement;
INSERT INTO #AllInfo
EXECUTE(@Statement);
FETCH cr_MaxDateTime INTO @Statement;
END;
CLOSE cr_MaxDateTime;
DEALLOCATE cr_MaxDateTime;
select * from #AllInfo
I know sp_MSForEachDB may help, but the examples I could find are mostly single line commands. I couldn't make it work for the whole script.