Example of a cursor that queries all rows by index for each database
Here, a cursor is used to loop through all databases.
Futhermore, a cursor from dynamic sql is used to query each database returned by the first cursor.
This is to demonstrate the connection-scope of a cursor.
DECLARE@db_name nvarchar(255)DECLARE@sql nvarchar(MAX)DECLARE@schema nvarchar(255)DECLARE@table nvarchar(255)DECLARE@column nvarchar(255)DECLARE db_cursor CURSORFORSELECT name FROM sys.databasesOPEN db_cursor
FETCHNEXTFROM db_cursor INTO@db_nameWHILE @@FETCH_STATUS=0BEGINSET@sql='SELECT * FROM '+ QUOTENAME(@db_name)+'.information_schema.columns'PRINT''PRINT''PRINT''PRINT@sql-- EXECUTE(@sql) -- For each database DECLARE@sqlstatement nvarchar(4000)--move declare cursor into sql to be executedSET@sqlstatement='DECLARE columns_cursor CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM '+ QUOTENAME(@db_name)+'.information_schema.columns ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION'EXEC sp_executesql @sqlstatementOPEN columns_cursor
FETCHNEXTFROM columns_cursor
INTO@schema,@table,@columnWHILE @@FETCH_STATUS=0BEGINPRINT@schema+'.'+@table+'.'+@column--EXEC asp_DoSomethingStoredProc @UserIdFETCHNEXTFROM columns_cursor --have to fetch again within loopINTO@schema,@table,@columnENDCLOSE columns_cursor
DEALLOCATE columns_cursor
-- End for each database FETCHNEXTFROM db_cursor INTO@db_nameENDCLOSE db_cursor
DEALLOCATE db_cursor