Posts

Showing posts from August, 2012

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 Ta...