Most of the time when I use a cursor I find myself using the same template. I am always writing the same code so I figured I’d save myself 3 minutes each time I use a cursor and store the code here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
DECLARE @name varchar(128) DECLARE _cursor CURSOR LOCAL FAST_FORWARD FOR SELECT [name] FROM sys.databases --uncomment line below to include Master, MSDB, Model, TEMPDB, and distribution WHERE [database_id] > 4 AND [name] != 'distribution' ORDER BY [name]; OPEN _cursor FETCH NEXT FROM _cursor INTO @name WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'USE [' + @name + ']' PRINT 'GO' PRINT '' FETCH NEXT FROM _cursor INTO @name END CLOSE _cursor; DEALLOCATE _cursor; |