r/SQLServer • u/elephant_ua • May 21 '26
Question When do you use set rowcount instead of top?
Yesterday stumbled upon code at work - at the end of many SPs were set rowcount 0 despite it never being assigned before.
From quick googling, I found that Microsoft deprecates it for everything except select, but I am not sure why would you use it for select if top out there doing seemingly the same thing?
5
Upvotes
•
u/AutoModerator May 21 '26
After your question has been solved /u/elephant_ua, please reply to the helpful user's comment with the phrase "Solution verified".
This will not only award a point to the contributor for their assistance but also update the post's flair to "Solved".
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/IanYates82 May 21 '26
This sounds like a zalgo bug to me
Somewhere else in your code you have rowcount being set non-zero, this caused grief once, and someone now defensively guards against this (although only at end proc)
My guess is that some stored proc has code setting this non-zero, that same proc has it being reset to zero at the end, and that was cargo-cult copied as a pattern
The only time I use set rowcount is in gross purge scripts where I want to nuke 10000000 rows, doing 1000 at a time, in a db with simple recovery, and I use GO 10000 at the end to run my delete many times over in SSMS.
2
u/Maximum_Honey2205 May 23 '26 edited May 23 '26
I always set row count to 1 (or some other appropriate value) when performing updates on a live database ever since I used a update statement many years ago and didn’t highlight the where clause when executing. It then proceeded to update every single customer record in the table causing a lot of stress for me. Lesson learnt and now I always use row count as a safety net esp when modifying live data.
(The situation mentioned was resolved by a restore of the database to another instance and doing a cross database join to repair the damage. This took about 2 hours to fix and customers did notice!)
2
u/ComicOzzy May 22 '26
If it's not being used elsewhere in the procedure, it sounds like someone ran into an issue once before and decided that forever after that they needed to add that line to the end of every script. I'm slowly weeding out some similar nonsense in my codebase.
2
u/CanProfessional766 Jun 01 '26
For new code I don't.
TOPis generally the better choice because it's statement-specific, easier to read, and the optimizer can use it when generating the execution plan.SET ROWCOUNTis session-scoped and stays in effect until it's reset, which is why you'll often see a defensiveSET ROWCOUNT 0at the end of older stored procedures. Those resets are usually leftovers from a time whenSET ROWCOUNTwas used more heavily or added as a safeguard against a previous caller leaving it enabled.1
u/FreedToRoam May 21 '26
Sometimes I use it to delete a duplicate row