USE AdventureWorks;GO--===== Declare some cursor related variablesDECLARE @EmployeeID INT, @Title NVARCHAR(50)--===== Declare the cursor using a SELECTDECLARE Employee_Cursor CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT EmployeeID, Title FROM HumanResources.Employee;--===== Open the cursor to begin using it. -- This is where a static cursor gets loaded -- into a temp table OPEN Employee_Cursor;--===== Start an infinite loop. We'll break out later... WHILE 1 = 1 BEGIN --===== Read a row from the cursor FETCH NEXT FROM Employee_Cursor INTO @EmployeeID, @Title; --===== If the read above returns NO row, exit the loop -- because we're done IF @@FETCH_STATUS <> 0 BREAK; --===== If we're still here, then there was a row to be read. -- We can now process that row. SELECT @EmployeeID, @Title;--===== This marks the end of the While Loop which automatically continues -- up to here until we hit the "BREAK" in the code above. END;--======== Release any locks held open by the cursor and then drop the -- cursor structure. CLOSE Employee_Cursor;DEALLOCATE Employee_Cursor;GO
USE AdventureWorks;GO--===== Declare some cursor related variablesDECLARE @EmployeeID INT, @Title NVARCHAR(50)--===== Declare the cursor using a SELECTDECLARE Employee_Cursor CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT EmployeeID, Title FROM HumanResources.Employee;--===== Open the cursor to begin using it. -- This is where a static cursor gets loaded -- into a temp table OPEN Employee_Cursor;--===== Start an infinite loop. We'll break out later... WHILE 1 = 1 BEGIN
WHILE (@@FETCH_STATUS = 0)
DECLARE @Database VARCHAR(255) DECLARE @DBList TABLE (DBName varchar(255), Processed CHAR(1))-- Populate the in-memory table @DBList with all of the database namesinsert @DBListSelect [name] , 'N' from master..sysdatabases where [name] NOT IN( 'model','master','tempdb','msdb')--select * from @DBList -- DEBUG: Run this to prove population was successful-- Grab the first DB name from our in-memory tableWhile EXISTS (Select top 1 DBName from @DBList where Processed='N' order by DBName)BEGIN-- Get the DB Name into the @Database variableSet @Database = (Select top 1 DBName from @DBList where Processed='N' order by DBName)-- Do whatever awesome stuff with the database...print @Database-- Update the Processed flag to skip this DB on the next WHILE pass. Ever-decreasing listUpdate @DBList set Processed='Y' where DBName = @DatabaseEND