SQL While Loops Made Easy! | When you to use a While Loop and when Not To! | SQL Server Tutorial

Published: 26 November 2024
on channel: The SQL Guy
2,616
11

Here we explain how and when to use While Loops in SQL Server and why they are sometimes beneficial over your standard Set Based Logic

Set Based Logic

Set based logic effectively takes a set of data and attempts to update it, the problem with that is if the set of data is huge then this is going to use a lot of server resource such as memory, threads etc. It will also put a lock on the table preventing other users from accessing the data - this can be very problematic.

Set based logic has it's place, and if anything SQL Server is designed around set based logic but there is a fine line between efficiency and poor performance.

When we have a huge number of rows to update then it's beneficial to take a small subset of those and update them in batches. Think of it as multiple loads of Set based logic.

This is where While Loops come in - or sometimes cursors.

While Loops

These are sometimes called Do While Loops, but essentially they take a small amount of the data and update, delete, alter it then go and do the next batch.

Your job is to code the loop to ensure it doesn't run continuously and to make sure it doesn't get the same number of rows more than once. it's pretty simple once you get the hang of it!

Content

00:00 Lesson overview
00:50 Set Based Logic
01:46 How to use a While Loop
06:00 Setting your counter for performance


On this page of the site you can watch the video online SQL While Loops Made Easy! | When you to use a While Loop and when Not To! | SQL Server Tutorial with a duration of hours minute second in good quality, which was uploaded by the user The SQL Guy 26 November 2024, share the link with friends and acquaintances, this video has already been watched 2,616 times on youtube and it was liked by 11 viewers. Enjoy your viewing!