A Little About Loops In Dynamic SQL
Thanks for watching!
Video Summary
In this video, I dive into some fascinating techniques using output parameters and dynamic SQL in SQL Server to loop through items like databases or tables. It’s particularly useful when dealing with non-contiguous IDs or missing values, ensuring you can dynamically find the next value without having to manually increment a counter. By leveraging these tricks, you can write more robust scripts that adapt to different database versions and configurations, making your analysis queries more reliable and less prone to errors in front of clients.
Full Transcript
Erik Darling here with Darling Data. And, uh, sorry, I had to delete a video that I didn’t like. Uh, no, no, it wasn’t this video. It was a different, different thing. Don’t worry. This, this one’s going to be great the first time through. Uh, anyway, uh, in today’s video, we’re going to talk a little bit about some cool stuff you can do with output parameters and dynamic SQL that you use to loop through things. Now, a lot of the times when you’re using dynamic SQL, it’s to like, make sure that the right thing happens at the right time based on like contextual stuff. Um, you know, if like, you’re like, I mean, if you’re like me, a lot of people like me, and you write a lot of SQL Server analysis scripts, you might find that different versions and additions of SQL Server might support different views and columns and, you know, bits of information. And you don’t want to hit errors when you run an analysis query because you’re doing it in front of a client. And gosh, that’s embarrassing. Uh, uh, so a lot of the times dynamic SQL is used to sort of detect object existence before like including a view or a table or a column or something, uh, in your query. And also is very, very, very useful for directing queries to the correct database, right? So you say, I want to do this in this database. And then when you get real crazy with dynamic SQL and you have it run across multiple databases, you can, you know, also have that happen. Uh, but you know, sometimes when you write dynamic SQL, it’s because you have to iterate over, like a bunch of stuff like databases and you want to make sure that you do that in the right order. And you want to make sure that the next value that you look for is the right one. Like you, like, it doesn’t always work to say like, you know, uh, like plus one, right? Cause you might have non-sequential IDs or something. Right. And that you would look very silly if you were like, you know, like, Oh, loop one ID one. And then there’s no ID, no more IDs until like 140, or maybe there’s no ID one.
And then you just keep running that loop over like the next incremented number because you just incremented your loop plus one. Cause isn’t that what everyone does in their, in their computer science labs? They, when they, they write their, their while loops and for loops and whatnot, they just say, Oh, plus one. Not the next, not the actual next number, just plus one, throw it on out there. Anyway, before we talk about that, uh, if you, if you like me and you like my free SQL Server content, and you would like to say thank you with money, uh, which I guess would make the SQL Server content, not free. Technically, uh, it would just, it would, it would just be a moderately priced. Thank you.
Uh, I have low cost memberships where you can say thank you to the tune of like four bucks a month. If you don’t have an extra four bucks a month, that’s totally cool. Um, I probably wouldn’t give an extra four bucks a month to some random guy on YouTube either. Uh, depending on how cute he is, who knows? Right. Uh, if you, if you would like to say thank you, in a different way, uh, you can like, you can subscribe, uh, you can, you can leave comments. And while that won’t exactly buy me a bottle of wine, that it’ll give me at least something nice to look at while I drink my wine. So if you have a, an unhealthy, angry, slow, begrudgingly awful performance, SQL Server issue, SQL Server performance issue words in the right order, please. Thank you. Uh, you can hire me to, to consult for you.
Uh, I do all of this stuff and more, and my rates are reasonable. Uh, if you want very low cost training for the rest of your life, uh, you can get all 24 plus hours of my content for, uh, 75% off. That’s about 150 bucks, us, us dollars, uh, after, after, uh, after the discount code kicks in. So, uh, that, that, that, that’s a good handy thing to do. And of course, as always, there is a link that, itself applies that coupon code right in the, in the video description. So, uh, and no, before I forget, this is why I do this stuff. Cause I forget a lot. I even forgot that this slide was next, even though I’ve been staring at this awful chat GPT image for, I don’t know how long, uh, Friday, September 6th, I will be in Dallas for data Saturday. Uh, I will have a full day pre-con about, all about SQL Server performance stuff. And I will also actually be at the actual main event on Saturday as well. Big breath, November 4th and 5th, I will be at past data summit in Seattle with Kendra Little doing two days of SQL Server performance pre-cons, uh, November 4th and 5th.
You should come spend some time with us there. And now, deep breath, let’s get on with the show. So, cause that’s what we do. We get on with shows here at Darling Data. So I’ve got what looks like a pretty standard while loop for SQL Server. Uh, but you’ll notice that there’s one thing that’s missing from this while loop. And that while loop is missing anything that increments I after the thing executes down the bottom there. Pretty wild, right? The way that I do that is with the magic of output parameters in dynamic SQL. Now I know there is almost no business case for this particular thing to be dynamic SQL, except to show you how this works. It’s wonderful. It’s fantastic.
So up way up at the top of, ah, come on, zoom it. Come on, zoom it. Wake up. Uh, at the, at the top of the, the, the, the loop, I have a pretty standard set of things being declared. I have at I, cause everyone names that thing at I, uh, I have at E, which I actually named at E after me. No, it’s, it’s for end, right? That’s the end number. Um, I guess, I don’t know what I is. I guess I should have named I S for start, but, uh, it’s too late now. Um, maybe in the next, maybe in the next world. Uh, and then of course I have an S well, shoot, I already have an S no wonder I didn’t name I S that would have, that would have just been terribly confusing. Um, that was, that’s going to hold our dynamic SQL. And of course our well formatted planned out thoughtful dynamic SQL, uh, is held in S with this. We’re going to select the top one at I, right? So we have at I as a parameter inside the dynamic SQL that gets, uh, that gets declared actually for the dynamic SQL down here. Awesome and amazing. And then we’re also saying where database ID is, is greater than at I. So in this dynamic SQL block, not only are we setting at I up here, but we’re filtering on at I down here. And then when we execute our dynamic SQL in the loop, we’re saying at I is an output parameter and we’re passing in, uh, at I is, uh, I mean, we’re, it has to be shown as an output parameter here so that we get the right value out, but it’s, it’s, it’s both, it’s an output parameter for, for the dynamic SQL and also an input parameter for the dynamic SQL.
And then down here, we’re just going to, you know, have a nice little message print out that says, Hey, this is where we’re at in the loop. Uh, and if you’re, if you’re the type of person who writes dynamic SQL that does any sort of looping or, you know, whatever, um, I would highly suggest using raise error with no weight, uh, over print for like status update stuff in your dynamic SQL, uh, because that tends to work a lot better. Uh, like print on its own has like weird buffer stuff that it has to deal with. And if you don’t fill those buffers up, the print statements can get weight lagged way far behind using raise error with no weight print stuff out just about immediately. If you need to print longer dynamic SQL out, I wouldn’t suggest using raise error because there are more strict limitations on the number of bytes that it can print out at a given time. I think it’s 4,000 or 2,000 something. I, I, 2,048 maybe. I forget. Uh, maybe that’s the max length of the message. Anyway, it’s much shorter than print. Print can do, uh, 8,000, uh, non-unicode bytes or 4,000 unicode bytes. And since dynamic SQL with SP execute, SP execute SQL is always unicode. You have some pretty strict limitations there, but much, much more open than, uh, than with raise error. So, uh, yeah, do that. And then if you have a real long dynamic SQL string, you can like get the length of it and like write a silly, another silly while loop that prints out the chunks of that until you have reached the end of the string. So without further ado, and I, again, I want to make perfectly clear, there is nothing in this that I, I, there is no set at I plus equals one, right? There’s no increment going on here.
So if we run this, I, when it gets passed into here, starts with a value of zero from up here, but then when I gets passed out of the dynamic SQL block, it has the next ID that’s greater than zero. So it actually increments itself by nature of just grabbing the next highest value.
This can be really, really useful when you don’t know what the next highest value is, right? Like, like in our case with, with sys.databases, we are very lucky that we print out one, two, three, four, five, six, seven, eight, right? But if you, if we were dealing with like real user data, where maybe it was one, two, three, 5029, you wouldn’t want to rerun, try to run a loop for all those things that don’t exist. So using the output parameter in this way can help you get to the next value if they’re non-contigious, right? So if even, even if you have an identity column or a sequence object, you may find that you’re, they are not like, like you don’t have an exact, like one, two, three, four, five, six, seven, eight, nine, 10, you can miss, you might have missing numbers in there.
So, you know, fun, fun, fun stuff abounds. The SQL Server. Thanks, SQL Server. You’re, you’re a real, real, real sport. So, well, this doesn’t exactly show off the, the, the amazingness of finding the next value if they’re non-contigious. It does kind of get the point across that this is a good way to do that should you find yourself in that situation. And then again, all you have to do is pass some values out of the dynamic SQL so that you know what the next one to go to is. Anyway, I think that’s pretty neat. I think that’s a kind of a neat trick with dynamic SQL because now you don’t have to sit there worrying about working out what the absolute next value is. You can just go right to it and make your life easier. It’ll make, make everyone happy. You can show this to someone that you’re romantically keen on. I don’t know. Maybe they’ll fall in love with you. Maybe, maybe, maybe this, maybe this is your happy moment in life. I don’t know. You can never predict these things. So anyway, thank you for watching. I hope you enjoyed yourselves. I hope you learned something and I hope that you will continue to watch this amazing free SQL Server content five days a week or maybe just watch it all one day a week. Because to be honest, I tend to like set aside some time and record a bunch of videos in one day. So that’s why, that’s why like you might see blocks of videos where you’re like, wow, that Erik Darling doesn’t change much. And you’re like, well, that’s, that’s because all these things are about five minutes apart. So tricks of the trade, as they say, tricks of the trade. Anyway, uh, I’m going to upload this. And then when this is done uploading, I’m going to record something else. Amazing how that works, isn’t it? All right, cool. Thank you for watching.
Going Further
If this is the kind of SQL Server stuff you love learning about, you’ll love my training. Blog readers get 25% off the Everything Bundle — over 100 hours of performance tuning content. Need hands-on help? I offer consulting engagements from targeted investigations to ongoing retainers. Want a quick sanity check before committing to a full engagement? Schedule a call — no commitment required.

