Cursor 2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

1.create a script to declare and use a cursor for the following SELECT statement.

Use a WHILE loop


to fetch each row in the result set. Omit the INTO clause to fetch directly to the Results tab.

SELECT LastName, AVG(ShipAmount) AS ShipAmountAvg


FROM Customers JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
GROUP BY LastName;

DECLARE @LastName NVARCHAR(255)


DECLARE @ShipAmountAvg DECIMAL(18, 2)

DECLARE CustomerCursor CURSOR FOR


SELECT LastName, AVG(ShipAmount) AS ShipAmountAvg
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GROUP BY LastName

OPEN CustomerCursor

FETCH NEXT FROM CustomerCursor INTO @LastName, @ShipAmountAvg

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CONCAT('Last Name: ', @LastName, ', Average Ship Amount: $',
FORMAT(@ShipAmountAvg, '###,###,###.00'))
FETCH NEXT FROM CustomerCursor INTO @LastName, @ShipAmountAvg
END

CLOSE CustomerCursor
DEALLOCATE CustomerCursor

You might also like