One by One or All at Once? The Tale of the WHILE Loop and the CURSOR

In the busy office of DataWorks Ltd., a helpful employee named Sita managed the company’s birthday email list.

Each morning, she had a list of 500 employee names and birthdates.

Her job?

“Check if today is their birthday, and if so, send them a greeting.”

She could:

  • Go through each person, one by one
  • Or use a smart way to check them all together

Her IT team showed her how this works in SQL.

Chapter 1: The WHILE Loop – Like a Checklist

Imagine Sita writing this on paper:

“Start at the top of the list.

While there are more names to check:

  • Look at birthday
  • If today, send email
  • Move to next person.”

This is a WHILE loop in SQL:

DECLARE @counter INT = 1;
WHILE @counter <= 500
BEGIN
   -- Check birthday at row @counter
   SET @counter = @counter + 1;
END

It’s like a loop that says: “Keep doing this until you’re done.”

Chapter 2: The CURSOR – Like a Name-by-Name Whisper

Then her team said:

“What if you want to do something special with each row—like send a personalized message or record each action?”

That’s where CURSOR comes in.

It acts like a finger pointing at each row, one at a time.

DECLARE birthday_cursor CURSOR FOR
SELECT Name, Email, BirthDate FROM Employees;

OPEN birthday_cursor;
FETCH NEXT FROM birthday_cursor INTO @Name, @Email, @BirthDate;

WHILE @@FETCH_STATUS = 0
BEGIN
   IF CAST(@BirthDate AS DATE) = CAST(GETDATE() AS DATE)
      EXEC SendBirthdayEmail @Name, @Email;

   FETCH NEXT FROM birthday_cursor INTO @Name, @Email, @BirthDate;
END

CLOSE birthday_cursor;
DEALLOCATE birthday_cursor;

Sita’s Takeaway

  • WHILE is like checking tasks on a numbered list.
  • CURSOR is like moving through a table one row at a time, doing something custom for each.

Why This Matters

  1. Batch operations are great—but row-by-row control is sometimes necessary.
  2. CURSORs can handle row-specific logic when SQL alone can’t.
  3. WHILE loops are great for repeating logic until a condition is met.
  4. Use both wisely—they can be slower than regular SQL if used with big data.

Conclusion:

Sita now uses SQL’s WHILE loops for checking scheduled tasks

and CURSORs for crafting personal messages, one person at a time.

“Sometimes data needs a bulk push.

Sometimes, it needs a gentle, thoughtful walk—row by row.”

That’s what WHILE and CURSOR help you do.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *