Looping
While Loop
USE AdventureWorks2012;
GO
WHILE (SELECT AVG(ListPrice) FROM Production.Product) < $300
BEGIN
UPDATE Production.Product
SET ListPrice = ListPrice * 2
SELECT MAX(ListPrice) FROM Production.Product
IF (SELECT MAX(ListPrice) FROM Production.Product) > $500
BREAK
ELSE
CONTINUE
END
PRINT 'Too much for the market to bear';Cursor Loop
USE SampleDB
GO
SET NOCOUNT ON;
-- Declare variables used in the code block
DECLARE @UserID INT
DECLARE @Username NVARCHAR(256)
-- Populate the cursor with values that will be evaluated
DECLARE user_cursor CURSOR FOR
SELECT
UserID,
Username
FROM dbo.Users
WHERE Username LIKE '%learner%'
-- Begin the cursor data processing and get the first user variables
OPEN user_cursor
FETCH NEXT FROM user_cursor INTO @UserID, @Username
-- Looping
WHILE @@FETCH_STATUS = 0
BEGIN
-- Do your action here...
PRINT CONVERT(VARCHAR(10), @UserID) + ' | ' + @Username
-- Get the next user
FETCH NEXT FROM user_cursor INTO @UserID, @Username
END
CLOSE user_cursor
DEALLOCATE user_cursorLast updated