Cursor Basics
When I started doing T-SQL, I remember Cursors being demonized and is said to be Evil by most of my colleagues, this made me shun away from using or even trying to understand how it works.
Finally, in one of the interviews I was asked how would you retrieve hundred or maybe thousand records and iterate on each while validating each row and doing insert if a row is valid?
My quick answer was to simply create a Table variable containing all the columns needed, plus an indexer column, do a INSERT INTO SELECT statement and also use the Row_Number() Over syntax. After inserting all the records to the Table variable I now iterate on each row by doing a while loop and declaring an counter and making increments as it goes to the loop, and using the incremented value as where clause in the select statement.
This is how the code would look like..
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 27 28 29 30 31 | DECLARE @TempTable Table(Id Int, CustomerId varchar(10), CompanyName varchar(100), ContactName varchar(100), OrderId int, OrderDate datetime) DECLARE @cntr int =0, @total int=0 INSERT INTO @TempTable(Id, CustomerId, CompanyName, ContactName, OrderId, OrderDate) SELECT ROW_NUMBER() OVER(ORDER BY c.CustomerId DESC) AS Id, c.CustomerID, c.CompanyName, c.ContactName, OrderID, OrderDate FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID SET @total =@@ROWCOUNT WHILE(@cntr<=@total) BEGIN SET @cntr = @cntr+1 SELECT Id, CustomerId, CompanyName, ContactName, OrderId, OrderDate FROM @TempTable WHERE Id = @cntr END |
Then the interviewer ask me why not use cursors? Will discuss this in including the Advantages and Disadvantages.
Comments